<?php
/**
 * Created by EditPlus.
 * User: GRAY <iamgray@gmail.com>
 * Date: 8/4/16
 * Time: 19:43
 */

namespace Home\Controller;

use Common\Library\BusinessException;
use Common\Library\Constant;
use Think\Controller;
use Common\Library\Http\Request;
use Common\Library\Http\Response;
use Think\Log;
use Think\Cache\Driver\Redis;
use Common\Vendor\Hook\BaseHook;
use Common\Library\SendSMS;



class PayController extends Controller {

    //protected $unsRequestHost = 'http://121.42.253.128:8081'; //银生宝正式服//-
    protected $unsRequestHost = 'http://114.80.54.73:8081'; //银生宝正式服//
    protected $unsContractId = '2120170417132156001';
    protected $unsAccountId = '2120170417132156001';
    // protected $unsKeys = 'huoyan@2017_2yinshengbao';
    protected $unsKeys = 'huoyan2020bs';
    protected $unsResponseHost = 'http://api.huoyanzichan.com'; //51部署地址
    protected $getGateId = 'http://api1.huoyanzichan.com/Home/MerchantBankInfo/getBankInfo'; //51部署地址
    protected $sendSms = 'http://zqhfundtest.huoyanzichan.com/BindCard/Bankcard/consumeSmsCode'; //51部署地址
    protected $bindCard = 'http://zqhfundtest.huoyanzichan.com/BindCard/Bankcard/consumeCardCode'; //51部署地址
    public function __construct() {
        parent::__construct();
        try {
            Request::parse();
        } catch (BusinessException $e) {
            $this->ajaxReturn(['code' => $e->getCode(), 'msg' => $e->getMessage()]);
        }
    }
/*
  * 分单逻辑
  * */
    public function fendan_jiaoben(){
        //默认平均值为15；
        $average = getConfig('MIX_FENDAN_NUM');
        //记录日志
        if (!is_dir('./fendanLog/zd_fendan_log/')) mkdir('./fendanLog/zd_fendan_log/',0777,true);
        $file_name = "./fendanLog/zd_fendan_log/fendanLog".date('Y-m-d').".txt";
        $myfile = fopen($file_name, "a") or die("Unable to open file!");
        //获取可分配总人数未处理总人数

        //获取可分单人员ID
        $u  = M('admin_users',null)
            ->where(['admin_users.fendan_status'=>1,'r.role_id'=>['in','4,7'],'admin_users.ppid'=>2])
            ->join('left join admin_role_user r on admin_users.id = r.user_id ')
            ->getField('id',true);
        if($u) {
            $new_user = array_unique($u);
            $new_user_1 = implode(',', $new_user);
            var_dump($new_user);
            //获取可分配人员手里剩余未处理订单数量
            $users = M('consume_fendan_log', null)
                ->field('user_id,count(consume_id) as con_count')
                ->where(['status' => 2, 'user_id' => ['in', $new_user_1]])
                ->group('user_id')
                ->select();
            //数组处理 ---start-----
            //数据处理成
            //        Array
            //        (
            //            [7] => 2 （key为审核人ID，value为剩余未处理订单数量）
            //            [11] => 0
            //            [12] => 2
            //            [15] => 0
            //            [19] => 0
            //            [20] => 0
            //            [21] => 0
            //            [22] => 0
            //            [23] => 0
            //            [24] => 0
            //            [31] => 0
            //        )
            $consume_count = 0; //获取可分配人员未处理总订单数
            if($users){
                foreach ($users as $kk => $vv) {
                    $consume_count += $vv['con_count'];
                    $new_key[$vv['user_id']] = $vv['con_count'];
                }

            }
            foreach ($new_user as $key => $val) {
                $new_keys[$val] = 0;
            }

            foreach ($new_keys as $kk => $vv) {
                if($new_key){
                    if ($new_key[$kk] != 0) {
                        $new_keys[$kk] = $new_key[$kk];
                    }
                }else{
                    $new_keys[$kk] = 0;
                }

            }
            asort($new_keys);//获取可分配人员手里剩余未处理订单数量
            //---end-----

            //计算应该最大分配总单数
            $more_order_num =$average * count($new_keys);
            //计算本轮实际分配总订单数
            $sj_more_order_num = $more_order_num - $consume_count;
            //获取数据库未分配总订单集合
            $new_A = M('consume_history', null)
                ->where('type=4 and status = 24 and id not in (select consume_id from consume_fendan_log)')
                ->limit($sj_more_order_num)
                ->getField('id', true);
            if($new_A) {
                //获取数据库未分配总订单数量
                $no_consume_count = count($new_A);

                if ($no_consume_count != $sj_more_order_num) {
                    //计算平均值
                    $new_sj_consume_count = $consume_count + $no_consume_count;
                    $average = floor($new_sj_consume_count / count($new_keys));

                }

                foreach ($new_keys as $key => $val) {
                    if ($average > $val) {
                        $fendan_total = $average - $val;//每人应分配单数
                    } else {
                        $fendan_total = $average;//每人应分配单数
                    }

                    $new_data = array_slice($new_A, 0, $fendan_total);
                    if ($new_data) {
                        foreach ($new_A as $kkk => $vvv) {
                            if (in_array($vvv, $new_data)) {
                                unset($new_A[$kkk]);
                            }
                        }
                        $new_arr = [];
                        foreach ($new_data as $kk => $vv) {
                            $arr['consume_id'] = $vv;
                            $arr['user_id'] = $key;
                            $arr['add_time'] = time();
                            $arr['admin_id'] = 1;
                            $new_arr[] = $arr;
                            unset($vv);
                        }
                        $res = M('consume_fendan_log', null)->addAll($new_arr);
                        if($res){
                            $content = "【".date('Y-m-d H:i:s',time())."】 给审核人员ID【".$key."】分配订单数【".$fendan_total."】成功\n";
                        }else{
                            $content = "【".date('Y-m-d H:i:s',time())."】 给审核人员ID【".$key."】分配订单数【".$fendan_total."】失败；原因：". M('consume_fendan_log', null)->_sql()."\n";

                        }
                        fwrite($myfile, $content);
                    }
                }
            }else{
                $content =  "【".date('Y-m-d H:i:s',time())."】 没有可分配订单\n";
                fwrite($myfile, $content);
            }
        }else{
            $content =  "【".date('Y-m-d H:i:s',time())."】 没有可分配人员\n";
            fwrite($myfile, $content);
        }



    }
    /*提交绑定银行卡|融360用户
    *
    *|**/
    public function bindVerifySmsRong($customerId,$card_holder,$card_id,$media_id,$bank_id,$identity_code) {
        try {
            if (!$card_holder || !$card_id || !$media_id) {
                //BusinessException::throwException(Constant::INVALID_PARAMETER);
                Log::rong_write_borrow("---实际绑定银行卡|bindVerifySmsRong|参数不全|201|customerId:".$customerId.'|$card_holder:'.$card_holder.'|$card_id:'.$card_id.'|$media_id:'.$media_id.'|$bank_id:'.$bank_id.'|$identity_code:'.$identity_code);
                return ['code'=>400,'msg'=>Constant::INVALID_PARAMETER];
            }
            $map = array(
                'customer_id' => $customerId,
                'card_num' => $card_id,
            );
            //银行不让重复绑定
            $CustomerBankInfo = M('CustomerBankInfo');
            if ($CustomerBankInfo->Where($map)->find()) {
                //BusinessException::throwException(Constant::BAND_CARD_EXIST);
                Log::rong_write_borrow("---实际绑定银行卡|bindVerifySmsRong|重复绑定|202|customerId:".$customerId.'|$card_holder:'.$card_holder.'|$card_id:'.$card_id.'|$media_id:'.$media_id.'|$bank_id:'.$bank_id.'|$identity_code:'.$identity_code);
                return ['code'=>400,'msg'=>'重复绑定了'];
            }
            /***************绑定银行卡|最多绑定两张***********************/
            $count=$CustomerBankInfo->Where($map)->count()>2?BusinessException::throwException(Constant::BAND_CARD_EXIST):$CustomerBankInfo->Where($map)->count();
            //Log::rong_write_borrow('****************客户'.$card_holder.'绑定银行卡银行卡|传参：$card_id:'.$card_id.'|$media_id:'.$media_id);
            $result = $this->unsBind($card_id,$media_id,$card_holder,$identity_code);
            Log::rong_write_borrow('****************bindVerifySmsRong|客户'.$card_holder.'绑定银行卡银行卡|传参：$card_id:'.$card_id.'|$media_id:'.$media_id.'|$card_holder:'.$card_holder.'|$identity_code:'.$identity_code.'|绑定银行卡银行卡|返回信息：'.json_encode($result).'|result_msg'.$result['result_msg']);
            if($result) {
                $ret_code = $result['result_code'];
                $ret_msg =  $result['result_msg'];
                if($ret_code=='0000') {
                    $usr_busi_agreement_id = ''; //用户业务协议号
                    $usr_pay_agreement_id = ''; //支付协议号
                    $gate_id = $bank_id; //COMM 银行编号
                    Log::rong_write_borrow('****************客户'.$card_holder.'绑定银行卡银行卡|gate_id：'.$gate_id.'银行绑卡返回信息');
                    $bank_card_type= 'DEBITCARD'; //银行卡类型 DEBITCARD(借记卡)
                    $subContractId = $result['subContractId'];
                    $bank = M('CustomerBankInfo')->where(['customer_id'=>$customerId,'card_num'=>$card_id])->field('id')->find();
                    /***********新卡|取消旧卡首选***************/
                    $cancel_res = M('CustomerBankInfo')->where(['customer_id'=>$customerId])->setField(['is_default'=>0]);
                    if($bank['id']>0) {
                        /**************绑定银行卡|新卡默认是首选*********/
                        M('CustomerBankInfo')->execute("UPDATE `customer_bank_info` SET `card_num` = '$card_id',`card_user_name` = '$card_holder',`is_default`=1,``reserved_mobile` = '$media_id',`usr_busi_agreement_id` = '$usr_busi_agreement_id',`usr_pay_agreement_id` = '$usr_pay_agreement_id',`sub_contract_id`='$subContractId',`gate_id` = '$gate_id',`bank_card_type` = '$bank_card_type',`add_time` = '".time()."' WHERE  `id` = '".$bank['id']."'");
                        $insertId = $bank['id'];
                    } else {
                        //入库
                        $data = array(
                            'customer_id' => $customerId,
                            'card_num' => $card_id,
                            'card_user_name' => $card_holder,
                            'reserved_mobile' => $media_id,
                            'usr_busi_agreement_id' => $usr_busi_agreement_id,
                            'usr_pay_agreement_id' => $usr_pay_agreement_id,
                            'sub_contract_id'=> $subContractId,
                            // 'sub_contract_id'=> 329374,
                            'gate_id' => $gate_id,
                            'bank_card_type' => $bank_card_type,
                            'add_time' => time(),
                            /**************绑定银行卡|新卡默认是首选************/
                            'is_default'=>1,
                            /**********绑定银行卡|新卡默认是首选***********/
                        );
                        if (false === ($insertId =$CustomerBankInfo->add($data))) {
                            //BusinessException::throwException(Constant::BAND_CARD_ADD_FAILED);
                            Log::rong_write_borrow("---实际绑定银行卡|重复绑定|202|customerId:".$customerId.'|$card_holder:'.$card_holder.'|$card_id:'.$card_id.'|$media_id:'.$media_id.'|$bank_id:'.$bank_id.'|$identity_code:'.$identity_code);
                            return ['code'=>400,'msg'=>'银行卡信息入库失败'];
                        }
                    }
                    $ret = Constant::getReturn(Constant::SUCCESS);
                    $ret['data'] = $CustomerBankInfo->where(['id' => $insertId])->field('card_num,card_user_name,reserved_mobile')->find();
                    //SendSMS::rmVerifyCode($media_id, Constant::VERIFY_CODE_TYPE_BIND); //删除验证码
                } elseif($ret_code=='2001' && $ret_msg=='子协议已经签订，无需重复签订') {
                    $subContractId = $result['subContractId'];
                    //已绑过卡 如果姓名一致，跟换用户ID
                    if($subContractId<>'') {
                        D()->execute("UPDATE `customer_bank_info` SET `customer_id`= '$customerId' WHERE  `sub_contract_id` = '$subContractId' and `card_user_name` ='$card_holder'");
                    }
                    $ret = Constant::getReturn(Constant::SUCCESS);
                } else {
                    //ret_code=00080550&ret_msg=无可用的支付通道
                    // BusinessException::throwException($result['result_msg']);
                    //$this->ajaxReturn(['code'=>205,'msg'=>$result['result_msg']]);
                    return ['code'=>400,'msg'=>$result['result_msg']];
                }
            }

        } catch (BusinessException $e) {
            //$this->ajaxReturn(['code' => $e->getCode(), 'msg' => $e->getMessage()]);
            //$this->ajaxReturn(['code'=>206,'msg'=>$result['result_msg']]);
            return ['code'=>400,'msg'=>$result['result_msg']];
        }
        Response::format($ret);
        //$this->ajaxReturn(['code'=>200,'msg'=>'']);
        return ['code'=>200,'msg'=>''];
    }
    /*+======================================+
     *| 易宝银生宝商户个渠道 [ 发送短信验证码 ]
     +======================================+*/
    public function bindCardSendSms($customerId,$cardNum,$mobile){
        $xml_data = [
            'card_num' => $cardNum
        ];
        $gateData_ =$this->postrequest($this->getGateId,$xml_data);
        Log::info_log('Pay/bindCardSendSms--获取卡宾  卡号'.$cardNum.' 客户id'.$customerId.'  '.$mobile.' 返回结果 '.json_encode($gateData_).$gateData_);
        $gateData=json_decode($gateData_,true);
        if(!$gateData['data']['gate_id']){
            Log::info_log('Pay/bindCardSendSms--获取卡宾失败  卡号'.$cardNum.' 返回结果 '.json_encode($gateData_).$gateData_);
            return false;
        }
        $userData = M('customer',null)->field('id,mobile,real_name,id_num')->where(['id'=>$customerId])->find();
        if(!$userData){
            Log::info_log('Pay/bindCardSendSms--异常客户id不存在 '.$customerId);
            return false;
        }
        $xml_data = [
            'customer_id' =>$customerId,
            'real_name' => $userData['real_name'],
            'bank_id' => $gateData['data']['gate_id'],
            'reser_phone' => $mobile,
            'trade_no' => $this->trade_no(),
            'id_card_no' =>  $userData['id_num'],
            'source' => 2,
            'card_num' => $cardNum
        ];
        $ajax_ret = D('Ajax')->ajaxPostByUrl($xml_data, $this->sendSms);
        Log::info_log('Pay/bindCardSendSms--向交易中心发起下发验证码请求 请求数据'.json_encode($xml_data).' 下发验证码返回结果 '.$ajax_ret);
        $data=json_decode($ajax_ret,true);
        if($data['code']==200){
            Log::info_log('Pay/bindCardSendSms--向交易中心发起下发验证码请求成功 请求数据'.json_encode($xml_data).' 下发验证码返回结果 '.$ajax_ret);
            return  true;
        }else{
            Log::info_log('Pay/bindCardSendSms--向交易中心发起下发验证码请求失败 请求数据'.json_encode($xml_data).' 下发验证码返回结果 '.$ajax_ret);
            return false;
        }
    }
    /* +=========================================+
    * app 用户  提交    绑定请求到交易中心
    * +========================================+*/
    public function sendBindRequest($customerId,$cardNum,$mobile,$verifycode){
        $xml_data = [
            'card_num' => $cardNum
        ];
        $gateData_ = $this->postrequest( $this->getGateId,$xml_data);
        Log::info_log('Pay/sendBindRequest--获取卡宾 卡号'.$cardNum.' 返回结果 '.json_encode($gateData_).$gateData_);
        $gateData=json_decode($gateData_,true);
        if(!$gateData['data']['gate_id']){
            Log::info_log('Pay/sendBindRequest--获取卡宾失败 卡号'.$cardNum.' 返回结果 '.json_encode($gateData_).$gateData_);
            return false;
        }
        $userData = M('customer',null)->field('id,mobile,real_name,id_num')->where(['id'=>$customerId])->find();
        if(!$userData){
            Log::info_log('Pay/sendBindRequest--客户id不存在 '.$customerId);
            return false;
        }
        $xml_data = [
            'customer_id' =>$customerId,
            'real_name' =>  $userData['real_name'],
            'bank_id' => $gateData['data']['gate_id'],
            'reser_phone' => $mobile,
            'trade_no' => $this->trade_no(),
            'id_card_no' => $userData['id_num'],
            'source' => 2,
            'card_num' => $cardNum,
            'verify_code' => $verifycode,
        ];
        $ajax_ret = D('Ajax')->ajaxPostByUrl($xml_data, $this->bindCard);
        Log::info_log('Pay/sendBindRequest--向交易中心发起绑卡请求 请求数据'.json_encode($xml_data).' 绑卡返回结果 '.$ajax_ret);
        $data=json_decode($ajax_ret,true);
        if($data['code']==200){
            Log::info_log('Pay/sendBindRequest--向交易中心发起绑卡请求成功 请求数据'.json_encode($xml_data).' 绑卡返回结果 '.$ajax_ret);
            return  $ajax_ret;
        }else{
            Log::info_log('Pay/sendBindRequest--向交易中心发起绑卡请求失败 请求数据'.json_encode($xml_data).' 绑卡返回结果 '.$ajax_ret);
            return false;
        }
    }
    /* +=========================================+
     * app 用户  提交    绑定银行卡
     * +========================================+*/
    public function bindVerifySms() {
        try {
            $customerId = I('post.customer_id', 0, 'int');
            $card_holder = I('post.card_user_name', '', 'string');
            $card_id = I('post.card_num', '', 'string');
            $media_id = I('post.reserved_mobile', '', 'string');
            $verify_code =  I('post.verify_code', '', 'string');
            $bind_no =   I('post.bind_no', '', 'string');
            $bank_id =   I('post.bank_id', '', 'string');
            //截取银行卡前六位
            $banks_id=substr($card_id,0,6);
            Log::info_log('***客户'.$card_holder.'绑定银行卡银行卡|截取前六位：$bank_id:'.$bank_id.'银行绑卡返回信息');
            //查询卡号是否存在银行卡判断表中
            $bank_ids=M("bank_panduan",null)->where(['bank_id'=>$banks_id])->find();//查询是否是我们支持的银行
            $gate_ids=M("bank_panduan",null)->where(['gate_id'=>$bank_id,'bank_id'=>$banks_id])->find();//查询用户所选的银行是否正确
            if(empty($bank_ids)){
                BusinessException::throwException('建议换一张银行卡，暂不支持该银行卡');
            }
            if($bank_ids['gate_id']=='CMBC'){//暂不支持民生银行|广发|邮政
                Log::info_log('客户'.$card_holder.'民生银行卡|银行绑卡拦截'.$bank_ids['gate_id'].$card_id);
                BusinessException::throwException('建议换一张银行卡，暂不支持该银行卡');
            }
            if($bank_ids['gate_id']=='GDB'){//暂不支持民生银行|广发|邮政
                Log::info_log('客户'.$card_holder.'广发银行卡|银行绑卡拦截'.$bank_ids['gate_id'].$card_id);
                BusinessException::throwException('建议换一张银行卡，暂不支持该银行卡');
            }
            if($bank_ids['gate_id']=='PSBC'){//暂不支持民生银行|广发|邮政
                Log::info_log('客户'.$card_holder.'邮政银行卡|银行绑卡拦截'.$bank_ids['gate_id'].$card_id);
                BusinessException::throwException('建议换一张银行卡，暂不支持该银行卡');
            }
            if(empty($gate_ids)){
                BusinessException::throwException('请选对银行卡所属行信息');
            }
            if (!$card_holder || !$card_id || !$media_id) {
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            $CustomerBankInfo = M('CustomerBankInfo');
            $userinfo = D('Customer')->has($customerId);
            $identity_code = $userinfo['id_num'];
            if ($identity_code == '') {
                BusinessException::throwException('请先上传身份证信息');
            }
            /*开启预留手机短信验证码*/
            if (!$verify_code) {
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            if(Constant::BINDCARDSOURCE=='2'){
                Log::info_log('客户'.$card_holder.' '.$card_id.'  走交易中心绑卡'.json_encode(I('post.')));
            }else{
                //2.验证码校验
                $verifyType = Constant::VERIFY_CODE_TYPE_BIND;
                $sentVerifyCode = SendSMS::getVerifyCode($media_id, $verifyType);
                if (!$sentVerifyCode) {   //验证码超时
                    BusinessException::throwException(Constant::VERIFY_CODE_TIMEOUT);
                }
                if ($verify_code != $sentVerifyCode) {  //验证码不正确
                    BusinessException::throwException(Constant::VERIFY_CODE_UNMATCHED);
                }
                /*验证码认证end*/
            }
            $map = array(
                'customer_id' => $customerId,
                'card_num' => $card_id,
            );
            //银行不让重复绑定
            $CustomerBankInfo = M('CustomerBankInfo');
            if ($CustomerBankInfo->Where($map)->find()) {
                //BusinessException::throwException(Constant::BAND_CARD_EXIST);
            }
            /***绑定银行卡|最多绑定两张***/
            $count=$CustomerBankInfo->Where($map)->count()>5?BusinessException::throwException(Constant::BAND_CARD_EXIST):$CustomerBankInfo->Where($map)->count();
            if(Constant::BINDCARDSOURCE=='2'){
                $result_ = $this->sendBindRequest($customerId,$card_id,$media_id,$verify_code);
                Log::info_log('客户'.$card_holder.' '.$card_id.'  走交易中心绑卡-请求参数'.' 客户id'.$customerId.' 卡号'.$card_id.'  预留手机'.$media_id.' 验证码'.$verify_code .' 返回'.$result_);
                $result=json_decode($result_,true);
                $result['result_code']=($result['code']==200)?'0000':'11111';
                $result['result_msg']= '';
                $result['subContractId']= '7777777';
            }else{
                Log::info_log('客户'.$card_holder.' '.$card_id.'  走银生宝绑卡');
                $result = $this->unsBind($card_id,$media_id,$card_holder,$identity_code);
            }
            Log::info_log('客户'.$card_holder.'绑定银行卡银行卡|传参：$card_id:'.$card_id.'|$media_id:'.$media_id.'银行绑卡返回信息'.json_encode($result));
            if($result) {
                $ret_code = $result['result_code'];
                $ret_msg =  $result['result_msg'];
                if($ret_code=='0000') {
                    $usr_busi_agreement_id = ''; //用户业务协议号
                    $usr_pay_agreement_id = ''; //支付协议号
                    if(Constant::BINDCARDSOURCE=='2'){
                        $usr_busi_agreement_id=1;
                    }
                    $gate_id = $bank_id; //COMM 银行编号
                    Log::info_log(' 客户'.$card_holder.'绑定银行卡银行卡|gate_id：'.$gate_id.'银行绑卡返回信息');
                    $bank_card_type= 'DEBITCARD'; //银行卡类型 DEBITCARD(借记卡)
                    $subContractId = $result['subContractId'];
                    $bank = M('CustomerBankInfo')->where(['customer_id'=>$customerId,'card_num'=>$card_id])->field('id')->find();
                    /***新卡|取消旧卡首选***/
                    $cancel_res = M('CustomerBankInfo')->where(['customer_id'=>$customerId])->setField(['is_default'=>0]);
                    if($bank['id']>0) {
                        /***绑定银行卡|新卡默认是首选***/
                        M('CustomerBankInfo')->execute("UPDATE `customer_bank_info` SET `card_num` = '$card_id',`card_user_name` = '$card_holder',`is_default`=1,``reserved_mobile` = '$media_id',`usr_busi_agreement_id` = '$usr_busi_agreement_id',`usr_pay_agreement_id` = '$usr_pay_agreement_id',`sub_contract_id`='$subContractId',`gate_id` = '$gate_id',`bank_card_type` = '$bank_card_type',`add_time` = '".time()."' WHERE  `id` = '".$bank['id']."'");
                        $insertId = $bank['id'];
                    } else {
                        //入库
                        $data = array(
                            'customer_id' => $customerId,
                            'card_num' => $card_id,
                            'card_user_name' => $card_holder,
                            'reserved_mobile' => $media_id,
                            'usr_busi_agreement_id' => $usr_busi_agreement_id,
                            'usr_pay_agreement_id' => $usr_pay_agreement_id,
                            'sub_contract_id'=> $subContractId,
                            'gate_id' => $gate_id,
                            'bank_card_type' => $bank_card_type,
                            'add_time' => time(),
                            'is_default'=>1,
                        );
                        if (false === ($insertId =$CustomerBankInfo->add($data))) {
                            BusinessException::throwException(Constant::BAND_CARD_ADD_FAILED);
                        }
                    }
                    $ret = Constant::getReturn(Constant::SUCCESS);
                    //$ret = Constant::getReturn(Constant::CARD_BIND_SUCCESS); //规避客户端BUG
                    $ret['data'] = $CustomerBankInfo->where(['id' => $insertId])->field('card_num,card_user_name,reserved_mobile')->find();
                    //SendSMS::rmVerifyCode($media_id, Constant::VERIFY_CODE_TYPE_BIND); //删除验证码
                } elseif($ret_code=='2001') {//&& $ret_msg=='子协议已经签订，无需重复签订'
                    Log::info_log('客户绑卡 子协议已经签订，无需重复签订'.json_encode($result).$card_id.$media_id.$card_holder.$identity_code);
                    $usr_busi_agreement_id = ''; //用户业务协议号
                    $usr_pay_agreement_id = ''; //支付协议号
                    $gate_id = $bank_id; //COMM 银行编号
                    $bank_card_type= 'DEBITCARD'; //银行卡类型 DEBITCARD(借记卡)
                    $subContractId = $result['subContractId'];
                    //子协议号已经签订过
                    $banMap =[];
                    $banMap['customer_id'] = $customerId;
                    $banMap['card_num'] = $card_id;
                    $oldBankData = M('CustomerBankInfo')->where($banMap)->field('id,customer_id,card_num,sub_contract_id,is_default')->find();
                    if($oldBankData){//银行卡记录存在
                        $cancel_res = M('CustomerBankInfo')->where(['customer_id'=>$customerId])->setField(['is_default'=>0]);  //取消旧卡
                        M('CustomerBankInfo')->where($banMap)->setField(['is_default'=>1]);
                        M('CustomerBankInfo')->where($banMap)->setField(['sub_contract_id'=>$subContractId]);
                        Log::info_log('***客户'.$card_holder.'绑定银行卡银行卡|gate_id：'.$gate_id.'子协议已经签订，无需重复签订  记录已存在   设置主卡 更改子协议号');
                    }else{//银行卡记录不存在 新增一条
                        $cancel_res = M('CustomerBankInfo')->where(['customer_id'=>$customerId])->setField(['is_default'=>0]);  //取消旧卡
                        $data = array(
                            'customer_id' => $customerId,
                            'card_num' => $card_id,
                            'card_user_name' => $card_holder,
                            'reserved_mobile' => $media_id,
                            'usr_busi_agreement_id' => $usr_busi_agreement_id,
                            'usr_pay_agreement_id' => $usr_pay_agreement_id,
                            'sub_contract_id'=> $subContractId,
                            'gate_id' => $gate_id,
                            'bank_card_type' => $bank_card_type,
                            'add_time' => time(),
                            'is_default'=>1,
                        );
                        $insertId =$CustomerBankInfo->add($data);
                        Log::info_log('***客户'.$card_holder.'绑定银行卡银行卡|gate_id：'.$gate_id.'子协议已经签订，无需重复签订  记录不存在   新增记录');
                    }
                    $ret = Constant::getReturn(Constant::SUCCESS);
                } else {
                    //ret_code=00080550&ret_msg=无可用的支付通道
                    $result['result_msg']='验证码输入错误！';
                    Log::info_log('客户'.$card_holder.'   卡号 '.$card_id.' 绑定银行卡银行卡异常 验证码输入错误');
                    BusinessException::throwException($result['result_msg']);
                }
            }//***

        } catch (BusinessException $e) {
            $this->ajaxReturn(['code' => $e->getCode(), 'msg' => $e->getMessage()]);
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }
    function  get_overdue_amount51($id,$cid=0) {
        //还款金额计算：
        //正常还款金额：本金+本金*4%
        //逾期0-30天 还款金额= 正常还款金额+滞纳金+日罚金；（滞纳金=正常还款的金额*10%   日罚息=正常还款金额*2%*逾期天数）
        //逾期1m还款金额：还款金额= 正常还款金额+滞纳金+日罚金；（滞纳金=正常还款的金额*10%   日罚息=正常还款金额*2%*逾期天数）
        //逾期2m还款金额：还款金额= 逾期1m还款金额+滞纳金+日罚金（滞纳金=逾期1m还款金额*10%  日罚息=逾期1m还款金额*2%*逾期天数）
        //依次类推3m，4m，nm  （每一个m为30天）
        $overdue_amount =0;
        $time =time();
        $consumeinstallmentinfo =  M('ConsumeInstallmentHistory')->where(['id' => $id ])->find();
        if($consumeinstallmentinfo) {
            $repayment_time = $consumeinstallmentinfo['repayment_time'];
            $amount = $consumeinstallmentinfo['amount'];
            if($time>$repayment_time) {

                //1、A类：5天内正常还款，且回收罚息滞纳金，提额2000元。
                //2、B类：10天内正常还款，含有罚息滞纳金，可减免，额度1500元。
                //3、C类：M1内还款合同金额，无罚息滞纳金，额度维持1000元。
                //4、D类：M1后回收，不再续借。
                //$dd =ceil(($time - $repayment_time)/(3600*24)); //逾期天数
                $date1=date_create(date("Y-m-d",$repayment_time));
                $date2=date_create(date("Y-m-d",$time));
                $diff=date_diff($date1,$date2);
                $dd = $diff->days;
                //只有逾期1天算逾期
                if($dd>0) {
                    //触发
                    if($dd<=30  && $dd>=0) {
                        if($dd<=5) {
                            //max_cash_amount 不能升只能降
                            $result =D()->execute("UPDATE `customer` SET `max_cash_amount`=200000  WHERE  `id` = '$cid' and (`max_cash_amount`>200000 or `max_cash_amount`=0)");
                        }
                        if($dd<=10 && $dd>5) {
                            $result =D()->execute("UPDATE `customer` SET `max_cash_amount`=150000  WHERE  `id` = '$cid' and (`max_cash_amount`>150000 or `max_cash_amount`=0)");
                        }
                        if($dd>10) {
                            $result =D()->execute("UPDATE `customer` SET `max_cash_amount`=100000  WHERE  `id` = '$cid' and (`max_cash_amount`>100000 or `max_cash_amount`=0)");
                        }
                        $amount_m0 = $amount;
                        $overdue_amount = $amount_m0*0.1+ $amount_m0*$dd*0.02 ;
                    }
                    //1m
                    if($dd>30 && $dd<=60) {
                        $result =D()->execute("UPDATE `customer` SET `max_cash_amount`=-1  WHERE  `id` = '$cid'");
                        $amount_m0 = $amount;
                        $amount_m1 = $amount_m0 + ($amount_m0*0.1+ $amount_m0*30*0.02);
                        $overdue_amount = ($amount_m1 - $amount) + $amount_m1*0.1 + $amount_m1*($dd-30)*0.02;
                    }
                    //2m
                    if($dd>60 && $dd<=90) {
                        $result =D()->execute("UPDATE `customer` SET `max_cash_amount`=-1  WHERE  `id` = '$cid'");
                        $amount_m0 = $amount;
                        $amount_m1 = $amount_m0 + ($amount_m0*0.1+ $amount_m0*30*0.02);
                        $amount_m2 = $amount_m1 + ($amount_m1*0.1+ $amount_m1*30*0.02);
                        $overdue_amount = ($amount_m2 - $amount) + $amount_m2*0.1 + $amount_m2*($dd-60)*0.02;
                    }
                    //3m
                    if($dd>90) {
                        $result =D()->execute("UPDATE `customer` SET `max_cash_amount`=-1  WHERE  `id` = '$cid'");
                        $amount_m0 = $amount;
                        $amount_m1 = $amount_m0 + ($amount_m0*0.1+ $amount_m0*30*0.02);
                        $amount_m2 = $amount_m1 + ($amount_m1*0.1+ $amount_m1*30*0.02);
                        $amount_m3 = $amount_m2 + ($amount_m2*0.1+ $amount_m2*30*0.02);
                        $overdue_amount = ($amount_m3 - $amount) + $amount_m3*0.1 + $amount_m3*($dd-90)*0.02;
                    }
                } else {
                    //当天还款
                    $result =D()->execute("UPDATE `customer` SET `max_cash_amount`=200000  WHERE  `id` = '$cid' and (`max_cash_amount`>200000 or `max_cash_amount`=0)");
                    $overdue_amount=0;
                }
            } else {
                //提前还款
                $result =D()->execute("UPDATE `customer` SET `max_cash_amount`=200000  WHERE  `id` = '$cid' and (`max_cash_amount`>200000 or `max_cash_amount`=0)");
                $overdue_amount=0;
            }
        }

        return $overdue_amount;
    }
    /***************************
     * 用户还款（银生宝 易宝 等代扣）
    ****************************/
    public function payConfirm() {

        try {
            $customerId = I('post.customer_id', 0, 'int');
            $type = I('post.type', 1, 'int'); //类型 1还款 2交首付
            if($type=='') {$type = 1;} //默认还款
            $pay_pass = I('post.pay_pass', '', 'string'); //支付密码(密文)
            $card_num = I('post.card_num', '', 'string'); //传过来的银行卡
            $normal_amount = I('post.amount', 0, 'int'); //首付金额,单位分
            $arry = file_get_contents('php://input');
            $arr = json_decode($arry,true);
            $consume_id = $arr['consume_data'][0]['consume_id'];
            $check_pass = I('post.check_pass', 'yes', 'string'); //是否检查密码
            if($check_pass=='') {$check_pass = 'yes';} //是否检查密码默认检查
            $pay_action = I('post.pay_action', 1, 'int'); //还款方式 1用户手动 2系统代扣
            $repay_date = I('post.repay_date', '', 'string'); //最迟还款日
            //首付金额计算
            $overdue_amount = 0; //首付没有逾期金
            $amount = $normal_amount + $overdue_amount; //实付金额
            $order_type = 2; //首付是按单笔还
            $consume_data_arr = array();
            $consume_data_json = '';
            $redis = new Redis();
            Log::info_log('payConfirm用户主动还款 入参：'.json_encode(I('post.')));
            $futype = M('ConsumeHistory')->where(['id'=>$consume_id,'type'=>5,'status'=>3])->find();//----5--3---
            if ($futype){
                Log::info_log('payConfirm用户'.$customerId.'主动还款异常 订单已完成');
                BusinessException::throwException('订单已完成');
            }
            $key='repay-request'.$consume_id;
            if($redis->get($key)){
                Log::info_log('payConfirm用户'.$customerId.'主动还款异常 订单正在处理中 key：'.$key);
                BusinessException::throwException('订单正在处理中');
            }
            //还款金额计算
            if($type == 1) {
                $consume_data = I('post.consume_data'); //还款入参
                $consume_data_json = ($consume_data) ? json_encode($consume_data) : '';
                $consume_data_arr = $consume_data;
                if($consume_data_arr) {
                    $consume_data_count = count($consume_data_arr);
                    $order_type = ($consume_data_count >1) ? 1: 2;
                    $normal_amount = 0;
                    $overdue_amount = 0;
                    $overdue_amount_all = 0;
                    foreach($consume_data_arr as $v) {
                        if($v['type']==1) {
                            $normal_amount = $normal_amount + $v['amount'];
                            $overdue_amount_all = $overdue_amount_all + $v['overdue_amount'];
                        }
                        if($v['type']==5) {
                            if($v['installment_history']) {
                                foreach($v['installment_history'] as $v1) {
                                    $normal_amount = $normal_amount + $v1['amount'];
                                    $overdue_amount_all = $overdue_amount_all + $v1['overdue_amount']; //逾期金额客户端传值
                                    $this->get_overdue_amount51($v1['id'],$customerId); //逾期情况用户申请额度处理
                                }
                            }
                        }

                        if($v['type']==2 ) {
                            if($v['installment_history']) {
                                $big_id = $v['consume_id'];
                                $small_id = '';
                                foreach($v['installment_history'] as $v1) {
                                    $overdue_amount = $overdue_amount + $v1['overdue_amount'];
                                    $small_id .= $v1['id'].",";
                                }
                                $small_id = substr($small_id, 0, -1);
                                $repay_amount = D('ConsumeHistory')->PaymentCheck($big_id,$small_id); //还款金额外部计算，已包含逾期
                                $normal_amount = $normal_amount + $repay_amount;
                            }
                        }
                    }
                    $amount = $normal_amount + $overdue_amount_all;
                    /*** 增加预期50元 ***/
                    if($overdue_amount_all>0&&$pay_action==1){
                        $amount=$amount+Constant::OVER_DATE_RATE;
                    }
                } else {
                    Log::info_log('payConfirm用户'.$customerId.'主动还款异常 INVALID_PARAMETER');
                    BusinessException::throwException(Constant::INVALID_PARAMETER);
                }
            }

            $pay_type = I('post.paytype', 1, 'int'); //支付方式 1联动优势 2微信APP支付
            if($pay_type=='') {$pay_type = 1;} //默认联动优势
            $userinfo = D('Customer')->has($customerId);
            $mobile = $userinfo['mobile'];
            $mer_date = date('Ymd');
            $order_id = $this->trade_no();
            $balance_amount_old = $userinfo['balance_amount'];
            $balance_cash_amount_old = $userinfo['balance_cash_amount'];
            $credit_level_old = $userinfo['credit_level'];
            if($check_pass<>'no') {
                /***|打开支付密码校验|***/
                $userData_=M('Customer')->field('id,pay_pass')->where(['id'=>$customerId])->find();
                //验证支付密码
                if (!$userData_['pay_pass']) {
                    Log::info_log('payConfirm用户'.$customerId.'主动还款异常 UNSET_PAY_PASS');
                    BusinessException::throwException(Constant::UNSET_PAY_PASS);
                }
                if (password_unmatched($pay_pass, $userData_['pay_pass'])) {
                    Log::info_log('payConfirm用户'.$customerId.'主动还款异常 PAY_PASS_UNMATCHED');
                    BusinessException::throwException(Constant::PAY_PASS_UNMATCHED);
                }
            }
            /***获取用户绑定卡的支付协议号***/
            $CustomerBankInfo = M('CustomerBankInfo');
            $data_arr = $CustomerBankInfo->where("customer_id = $customerId and sub_contract_id<>''")->field('sub_contract_id')->find();
            /*** 绑定多张银行卡|finishmodel|customerbanckinfo| ***/
            Log::pay_write("改版过后传过来的银行卡".$card_num);
            $data_arr = $CustomerBankInfo->where(['card_num'=>$card_num,'customer_id'=>$customerId])->field('sub_contract_id,card_user_name')->limit(1)->find();
            /*** 绑定多张银行卡|finishmodel|customerbanckinfo| ***/
            $subContractId = $data_arr['sub_contract_id'];
            if ($subContractId =='') {
                Log::info_log('payConfirm用户'.$customerId.'主动还款异常 请先绑定银行999卡');
                BusinessException::throwException('请先绑定银行999卡');
            }
            /*** 给用户打款操作|本人银行卡校验| ***/
            if($userinfo['real_name']!=$data_arr['card_user_name']){
                Log::info_log('payConfirm用户'.$customerId.'主动还款异常 持卡人必须是本人'."payConfirm用户真实姓名：".$userinfo['real_name']."|持卡人姓名：".$data_arr['card_user_name']."");
                BusinessException::throwException('持卡人必须是本人');
            }
            //还款 入参金额检查
            if ($consume_data_arr && $type==1) {
                foreach($consume_data_arr as $v) {
                    $consume_id = $v['consume_id'];
                    $normal_amount = $v['amount'];
                    $repay_date = $v['repay_date'];
                    $consumeHistory = M('ConsumeHistory')->where(['id' => $consume_id])->find();
                    if (!$consumeHistory) {
                        BusinessException::throwException(Constant::INVALID_PARAMETER);
                    }
                    //次月
                    if ($normal_amount != $consumeHistory['amount'] && $consumeHistory['type']==1) {
                        BusinessException::throwException(Constant::INVALID_PARAMETER);
                    }
                    if ($consumeHistory['status']==3 && $consumeHistory['type']==1) {
                        BusinessException::throwException(Constant::INVALID_PARAMETER);
                    }
                    //分期
                    if($consumeHistory['type']==2  || $consumeHistory['type']==5) {
                        if($v['installment_history']) {
                            $ConsumeInstallmentHistory =D('ConsumeInstallmentHistory');
                            foreach($v['installment_history'] as $v1) {
                                $id = $v1['id'];
                                $normal_amount = $v1['amount'];
                                $repay_date = $v1['repay_date'];
                                //$repayment_time = strtotime(date('Y-m-' . Constant::BILL_LAST_DAY . ' 00:00:00', time()));
                                $repayment_time = ($repay_date<>'') ? strtotime($repay_date." 00:00:00") : strtotime(date('Y-m-' . Constant::BILL_LAST_DAY . ' 00:00:00', time()));
                                $data_arr = $ConsumeInstallmentHistory->where(['parent_id' => $consume_id,'repayment_time'=>$repayment_time])->field('amount,status')->find();
                                if ($normal_amount != $data_arr['amount'] && $data_arr['amount']>0) {
                                    BusinessException::throwException(Constant::INVALID_PARAMETER);
                                }
                                if ($data_arr['status']==1) {
                                    BusinessException::throwException(Constant::INVALID_PARAMETER);
                                }
                            }
                        }
                    }
                }
                //还多笔
                if($order_type==1) {
                    $consume_id = 0;
                    $repay_date = '';
                }
            }
            if ($amount==0) {
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            ////-----------部分还款-----------
            $partRepayFind = M("ConsumeHistory")->field("part_pay_amount,part_need_pay_amount")->where(['id'=>$consume_id,'type'=>'5','status'=>'1'])->find();
            if (isset($partRepayFind['part_pay_amount']) && !empty($partRepayFind['part_pay_amount'])) {
                $shengyu_amount = $this->getShengAmount($consume_id);
                Log::info_log('用户主动还款 已经划扣了部分金额|现主动还款剩余金额 consume_id：'.$consume_id.'|uns_amount|'. $shengyu_amount .'');
                $amount = $shengyu_amount;
            }
            ////-----------部分还款-----------
            $CustomerBillPayLog = M('CustomerBillPayLog');
            //入库
            $data = array(
                'order_id' => $order_id,
                'order_type' => $order_type,
                'customer_id' => $customerId,
                'consume_id' => $consume_id,
                'consume_data' => $consume_data_json,
                'repay_date' => $repay_date,
                'amount' => $amount,
                'trade_id' => '',
                'pay_type' => $pay_type,
                'type' => $type,
                'balance_amount_old' =>$balance_amount_old,
                'balance_cash_amount_old' =>$balance_cash_amount_old,
                'overdue_amount' => $overdue_amount,
                'pay_action' => $pay_action,
            );
            $CHrepay = M("ConsumeHistory")->where("id = $consume_id and repay = 1 ")->find();
            $repay_add_time = time() - $CHrepay['repay_add_time'];
            $repay_add_time = ($repay_add_time < 1800) ? true : false ;
            if ( $repay_add_time ) {
                if ( $CHrepay ) {
                    Log::info_log('用户主动还款异常 该笔消费订单|'. $consume_id .'|：'.'throwException(支付订单中)');
                    BusinessException::throwException('支付订单中');
                }
            }

            if (false === ($insertId = $CustomerBillPayLog->add($data))) {
                BusinessException::throwException('支付订单创建失败');
            }

            if ($customerId == "2162"){
                $uns_amount = 400.00;//测试写死1分钱
            }else {
                $uns_amount = $amount * 0.01;
            }
            /*** 还款校验| ***/
            $pay_check=M('ConsumeHistory')->where(['id'=>$consume_id,'type'=>'5','status'=>'3'])->find();
            if($pay_check){
                Log::info_log(' 用户主动还款异常 该笔消费已还款 '.$customerId.' '.json_encode($pay_check));
                BusinessException::throwException('该笔消费已还款，请勿重复还款~');
            }
            /*** 还款校验| ****/
            Log::info_log('用户主动还款 金额：'.$uns_amount.'订单'.$order_id.'子协议号'.$subContractId.'卡号'.$card_num);
            // $result = $this->unsPay($subContractId,$order_id,$uns_amount);
            $result= $this->yibaoPay($customerId,$card_num,$uns_amount,$order_id);
            Log::info_log("易宝渠道切换-".' '.$customerId.'    '.$card_num.'     '.$uns_amount.'      '.$order_id.'   返回'.$result.json_encode($result));
            $repayStatus = M("ConsumeHistory")->where("id = $consume_id")->setField(array('repay'=>1, 'repay_add_time'=>time()));
            Log::info_log(' 用户主动还款 consume_id：'.$consume_id.'设置结果  repay:'. ($repayStatus ? 1 : 0) );
            /*** 处理中订单|***/
            $key='repay-request'.$consume_id;
            if (!$redis->get($key)){
                $key='repay-request'.$consume_id;
                $redis_res=$redis->set($key,$consume_id,1800);//处理中的订单|---测试下---失效时间设置小---|第一次|控制住|第二次|允许|
                Log::info_log($customerId.' 用户主动还款 订单号码：'.$order_id.'|查询用户是否实际还款返回结果|存入redis结果|'.json_encode($redis_res));
            }
            Log::info_log($customerId.'用户主动还款执行返回结果：'.json_encode($result));
            if($result) {
                $ret_code ='0000';
                $ret_msg = '';
                $trade_state = '0000';//$result['status']
                if($ret_code=='0000') {
                    //$resultstatu = $this->unsPaystatu($order_id);
                    $yborderid='';
                    $resultstatu =D('Yibao')->yibaoSearch($order_id,$yborderid);
                    Log::info_log("易宝渠道查询-".' '.$customerId.'    '.$card_num.'     '.$uns_amount.'      '.$order_id.'   返回'.$resultstatu.json_encode($resultstatu));
                    //查询是否还款成功
                    if($resultstatu['status'] == 'PAY_SUCCESS'){
                        Log::info_log($customerId.'用户主动还款-查询用户'.$order_id.'是否实际还款返回结果-成功');
                        //还款成功写库
                        $sqldata = array('trade_state'=>$trade_state,'ret_msg'=>'success','pay_time'=>time(),'ret_code'=>$ret_code,'status'=>2);
                        $CustomerBillPayLog->where(['id'=>$insertId,'status'=>0])->setField($sqldata);
                        $ret = Constant::getReturn(Constant::SUCCESS);
                        $ret['data'] = array('order_id'=>$order_id,'trade_no'=>$order_id,'amount' => $amount,'pay_action' => $pay_action,'customer_id' => $customerId,'pay_time' => date('Y-m-d H:i:s',time()));
                        //更新订单状态到已还款完成
                        M('ConsumeHistory')->where(['id'=>$consume_id])->setField(['status'=>3,'update_time'=>time(), 'part_pay_amount'=>($partRepayFind['part_pay_amount'] + $amount) ,'part_need_pay_amount'=>0]);
                        M('Customer')->where(['id'=>$customerId])->setField(['cash_amount'=>0]);
                        M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id,'update_time'=>0])->setField(['status'=>1,'update_time'=>time(),"final_amount"=>0]);
                        /****这里扣款成功修改status给贷后分单用，防止撤单分单出现已还款仍能撤分单***/
                        $ConsumeUserInfo = M('consume_user')->where("consume_id = $consume_id and status = 1")->find();
                        if (isset($ConsumeUserInfo) && !empty($ConsumeUserInfo)) {
                            $ConsumeUserStatusInfo = M('consume_user')->where("consume_id = $consume_id and status = 1")->setField(array('status'=>2));
                        }
                        /****这里扣款成功修改status给贷后分单用，防止撤单分单出现已还款仍能撤分单***/
                    }else if($resultstatu['status'] == 'PAY_FAIL'){
                        Log::info_log($customerId.'用户主动还款-查询用户 '.$order_id.'是否实际还款返回结果 PAY_FAIL ');
                        $status = 3;
                        $sqldata = array('ret_msg'=>$resultstatu['errormsg'],'ret_code'=>1111,'status'=>$status);
                        $CustomerBillPayLog->where(['id'=>$insertId,'status'=>0])->setField($sqldata);
                        //手动输入的预扣金额为零
                        M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id,'update_time'=>0])->setField(["final_amount"=>0]);
                        $this->ajaxReturn(['code' => 1111, 'msg' =>$resultstatu['errormsg']]);
                    }elseif($resultstatu['status'] == 'PROCESSING'){
                        Log::info_log($customerId.'用户主动还款- '.' 订单号码：'.$order_id.' 查询用户是否实际还款返回结果PROCESSING');
                        $this->ajaxReturn(['code' => 10, 'msg' => $resultstatu['errormsg']]);
                    }
                } else if($ret_code=='1111') {
                    Log::info_log($customerId.'用户主动还款-1111 ');
                    //付款提交失败
                    $status = 3;
                    $sqldata = array('ret_msg'=>$trade_state,'ret_code'=>$ret_code,'status'=>$status);
                    $CustomerBillPayLog->where(['id'=>$insertId,'status'=>0])->setField($sqldata);
                    //手动输入的预扣金额为零
                    M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id,'update_time'=>0])->setField(["final_amount"=>0]);
                    $this->ajaxReturn(['code' => $ret_code, 'msg' => $trade_state]);
                }else {
                    Log::info_log($customerId.'用户主动还款-提交付款失败 ');
                    //付款提交失败
                    $status = 3;
                    $ret_msg2 ="提交付款失败";
                    $ret_code2 = 1112;
                    $sqldata = array('ret_msg'=>$trade_state,'ret_code'=>$ret_code,'status'=>$status);
                    $CustomerBillPayLog->where(['id'=>$insertId,'status'=>0])->setField($sqldata);
                    //手动输入的预扣金额为零
                    M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id,'update_time'=>0])->setField(["final_amount"=>0]);
                    BusinessException::throwException($ret_code2.$ret_msg2);
                }
            }else{
                $key='repay-request'.$consume_id;
                if($redis->get($key)){
                    $redis->rm($key);
                    BusinessException::throwException('该笔消费支付失败~');
                    Log::info_log("测试失败情况异步通知结果|订单".$order_id."|删除redis处理中|key:".$key.'|');
                }
            }

        } catch (BusinessException $e) {
            $this->ajaxReturn(['code' => $e->getCode(), 'msg' => $e->getMessage(),'data'=>['amount'=>$amount,'customerId'=>$customerId]]);
        }

        Response::format($ret);        $this->ajaxReturn($ret);
    }
    /***************************
     * 易宝渠道  发起代扣请求 （还款）
     ***************************/
    public  function yibaoPay($identityid,$cardNum,$amount,$order_id){
        $Yibao=D('Yibao');
        $cardtop = substr($cardNum, 0, 6);//前六位
        $cardlast= substr($cardNum, -4);//后四位
        $arr = $Yibao->BindPayDirect($identityid,$cardtop,$cardlast,$amount,$order_id);//**
        Log::info_log('yibaoPay易宝渠道--开始发起请求--参数'.$identityid.'  top '.$cardtop.' last   '.$cardlast.'  amount '.$amount.'   orderid'.$order_id.'  返回'.$arr.json_encode($arr));
        return $arr;
    }
    public function postrequest($url,$data){
        $options = array(
            'http' => array(
                'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
                'method'  => 'POST',
                'content' => http_build_query($data)
            )
        );
        $context  = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return $result;
    }
    /***************************
     * 易宝渠道  发起代扣请求 （续借）
     ***************************/
    public  function yibaoNewPay($identityid,$cardNum,$amount,$order_id){
        $Yibao=D('Yibao');
        $cardtop = substr($cardNum, 0, 6);//前六位
        $cardlast= substr($cardNum, -4);//后四位
        $arr = $Yibao->BindNewPayDirect($identityid,$cardtop,$cardlast,$amount,$order_id);//**
        Log::info_log('yibaoNewPay--开始发起请求--参数'.$identityid.'  top '.$cardtop.' last   '.$cardlast.'  amount '.$amount.'   orderid'.$order_id.'  返回'.$arr.json_encode($arr));
        return $arr;
    }
    /***************************
     * 主动还款回调地址 易宝渠道
     ***************************/
    public  function YibaoPayNotice(){
        $data_ = file_get_contents('php://input');//回掉xml形式 请修改
        Log::info_log('YibaoPayNotice易宝地址回调--'.$data_.json_encode($data_).json_encode(I('post.')));
        $return_data = $data_;
        $data_=json_decode($data_,true);
        $encryptkey=$data_['encryptkey'];
        if(!$encryptkey){
            $encryptkey=$_POST['encryptkey'];
        }
        if(!$data_['data']){
            $data_['data']=$_POST['data'];
        }
        $data = D('Yibao')->callBackYibao($data_['data'],$encryptkey);
        Log::info_log('YibaoPayNotice易宝回调--验签-结果'.json_encode($data));
        $Yibao=D('Yibao');
        $yborderid='';
        $arr = $Yibao->yibaoSearch($data['requestno'],$yborderid);
        Log::info_log('YibaoPayNotice易宝回调易宝回调--查询-结果'.json_encode($arr).'  订单号'.$data['requestno']);
        $ret_msg = $arr['errormsg'];
        $ret_code = $_POST['result_code'];
        $CustomerBillPayLog = M('CustomerBillPayLog');
        $order_id = $data['requestno'];
        $redis = new Redis();
        if($arr['status']=='PAY_SUCCESS'){
            Log::info_log('易宝回调--PAY_SUCCESS'.json_encode($arr).'  订单号'.$data['requestno']);
            $ret_code ='0000';
            $sqldata = array('ret_msg'=>'success','pay_time'=>time(),'status'=>1);
            $CustomerBillPayLog->where(['order_id'=>$order_id,'pay_time'=>0])->setField($sqldata);
            $CustomerBillPayLogInfo = $CustomerBillPayLog->where(['order_id' => $order_id])->find();
            $consume_id = $CustomerBillPayLogInfo['consume_id'];
            $customer_id = $CustomerBillPayLogInfo['customer_id'];
            if($consume_id>0) {
                /****这里扣款成功修改status给贷后分单用，防止撤单分单出现已还款仍能撤分单***/
                $ConsumeUserInfo = M('consume_user')->where("consume_id = $consume_id and status = 1")->find();
                if (isset($ConsumeUserInfo) && !empty($ConsumeUserInfo)) {
                    $ConsumeUserStatusInfo = M('consume_user')->where("consume_id = $consume_id and status = 1")->setField(array('status'=>2));
                }
                /****这里扣款成功修改status给贷后分单用，防止撤单分单出现已还款仍能撤分单***/
                Log::info_log(' 易宝回调异步通知 订单 '.$order_id.' 成功');
                /*** 异步通知结果 ***/
                $test_consume=M('ConsumeHistory')->where(['id'=>$consume_id,'type'=>5,'status'=>1])->setField(['status'=>3,'update_time'=>time()]);
                $test_install=M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->setField(['status'=>1,'update_time'=>time()]);
                $trd=M('Customer')->where(['id'=>$customer_id])->setField(['balance_cash_amount'=>200000,'cash_amount'=>0]);
                Log::info_log('易宝异步通知|操作ConsumeHistory|结果：'.json_encode($test_consume).'');
                /*** 处理中 ***/
                //查询用户订单信息
                $consume = M('ConsumeHistory')->where(['id'=>$consume_id])->find();
                if ($consume['status'] == 3){
                    $paylog = $CustomerBillPayLog->where(['order_id'=>$order_id])->find();
                    $consumehistory = M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->find();
                    if ($paylog['amount'] != $consumehistory['amount']){
                        $scredit = D('CustomerAuth')->saveCustomerAuth($consume['customer_id']);
                        if (!$scredit){
                            BusinessException::throwException(Constant::INVALID_PARAMETER);
                        }
                        $czhima = D('Customer')->saveCustomerzhima($consume['customer_id']);
                        if (!$czhima){
                            BusinessException::throwException(Constant::INVALID_PARAMETER);
                        }
                    }
                }
                $CustomerBillPayLogInfo = $CustomerBillPayLog->where(['order_id' => $order_id])->find();
                $key='repay-request'.$CustomerBillPayLogInfo['consume_id'];
                if($redis->get($key)){
                    $redis_res=$redis->rm($key);
                    Log::info_log("易宝代扣异步通知结果 订单".$order_id." 删除redis处理中 key:".$key.' ');
                }
                Log::info_log("易宝代扣异步通知结果-order_id:".$order_id.'-成功');
            }
        }else{
            Log::info_log('易宝回调--PAY_FAILED'.json_encode($arr).'  订单号'.$data['requestno']);
            $ret_code ='1111';
            $CustomerBillPayLogInfo = $CustomerBillPayLog->where(['order_id' => $order_id])->find();
            $consume_id = $CustomerBillPayLogInfo['consume_id'];
            $repayStatus = M('ConsumeHistory')->where(['id'=>$consume_id])->setField(['repay'=>0, 'repay_add_time'=>0]);
            Log::info_log("订单".$consume_id."易宝回调异步ConsumeHistory设置repay通知结果 repay:". ($repayStatus ? 0 : 1) .'|');
            $sqldata = array('ret_msg'=>$ret_msg,'ret_code'=>$ret_code);
            $CustomerBillPayLog->where(['order_id'=>$order_id,'pay_time'=>0])->setField($sqldata);
            /*** 处理中***/
            $CustomerBillPayLogInfo = $CustomerBillPayLog->where(['order_id' => $order_id])->find();
            $key='repay-request'.$CustomerBillPayLogInfo['consume_id'];
            if($redis->get($key)){
                $redis_res=$redis->rm($key);
                Log::info_log("易宝代扣异步通知结果|订单".$order_id." 删除redis处理中|key:".$key.'|');
            }
            Log::info_log("易宝代扣异步通知结果||order_id:".$order_id.'失败');
            /*** 处理中***/
        }
        echo 'SUCCESS';

    }
    /*******************
     * 续借回调地址 易宝渠道
    ********************/
    public  function YibaoNewPayNotice(){
        $data_ = file_get_contents('php://input');//回掉xml形式 请修改
        Log::info_log('YibaoNewPayNotice易宝地址回调--'.$data_.json_encode($data_).json_encode(I('post.')));
        $return_data = $data_;
        $data_=json_decode($data_,true);
        $encryptkey=$data_['encryptkey'];
        if(!$encryptkey){
            $encryptkey=$_POST['encryptkey'];
        }
        if(!$data_['data']){
            $data_['data']=$_POST['data'];
        }
        $data = D('Yibao')->callBackYibao($data_['data'],$encryptkey);
        Log::info_log('YibaoNewPayNotice易宝回调--验签-结果'.json_encode($data));
        $Yibao=D('Yibao');
        $yborderid='';
        $arr = $Yibao->yibaoSearch($data['requestno'],$yborderid);
        Log::info_log('YibaoNewPayNotice易宝回调易宝回调--查询-结果'.json_encode($arr).'  订单号'.$data['requestno']);
        $ret_msg = $arr['errormsg'];
        $ret_code = $_POST['result_code'];
        $CustomerBillPayLog = M('CustomerBillPayLog');
        $order_id = $data['requestno'];
        $redis = new Redis();
        if($arr['status']=='PAY_SUCCESS'){
            $ret_code = '0000';
            Log::info_log('易宝续借代扣回调 开始更新CustomerBillPayLog表|'.json_encode($CustomerBillPayLog));
            $sqldata = array('ret_msg'=>'success','pay_time'=>time(),'status'=>1);
            $CustomerBillPayLog->where(['order_id'=>$order_id,'pay_time'=>0])->setField($sqldata);
            $CustomerBillPayLogInfo = $CustomerBillPayLog->where(['order_id' => $order_id])->find();
            Log::info_log('易宝续借代扣结束更新CustomerBillPayLog表|'.json_encode($CustomerBillPayLogInfo));
            $consume_id = $CustomerBillPayLogInfo['consume_id'];
            $customer_id = $CustomerBillPayLogInfo['customer_id'];
            if($consume_id>0) {
                Log::info_log('易宝续借代扣异步通知|订单|'.$order_id.'|成功');
                /*** 开启回掉函数更改续借日期***/
                $repay_time=  M('ConsumeHistory')->where(['id'=>$consume_id])->field('repayment_time,repay_id')->find();
                $repay_time_=  M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->field('repayment_time')->find();
                $repay_time_old=$repay_time_['repayment_time'];
                if(!$repay_time_old){//如果不存在|默认取当前当前
                    $repay_time_old=time();
                }
                //根据用户选择的产品|延迟天数
                $repay_long=($repay_time['repay_id']=='1')?30:($repay_time['repay_id']=='2'?14:30);
                /****这里扣款成功修改status给贷后分单用，防止撤单分单出现已还款仍能撤分单***/
                $ConsumeUserInfo = M('consume_user')->where("consume_id = $consume_id and status = 1")->find();
                if (isset($ConsumeUserInfo) && !empty($ConsumeUserInfo)) {
                    $ConsumeUserStatusInfo = M('consume_user')->where("consume_id = $consume_id and status = 1")->setField(array('status'=>3));//逾期续借状态变为3记录在表里
                }
                /****这里扣款成功修改status给贷后分单用，防止撤单分单出现已还款仍能撤分单***/
                /*** 开启回掉函数更改续借日期***/
                M('Customer')->where(['id'=>$customer_id])->setField(['balance_cash_amount'=>100000]);
                /***|展期成功后|展期控制清零|***/
                M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->setField(['allow_renew'=>0]);
                /*** 同时更新续借时间***/
                $repay_time=  M('ConsumeHistory')->where(['id'=>$consume_id])->field('repayment_time,repay_id')->find();
                $repay_time_=  M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->field('repayment_time')->find();
                $ConsumeHistory = M('consume_history')->where(['id' => $consume_id])->find();
                //之前还款时间
                $repay_time_old=$repay_time_['repayment_time'];
                if(!$repay_time_old){//如果不存在|默认取当前当前
                    $repay_time_old=time();
                }
                //根据用户选择的产品|延迟天数--查库
                $repay_time['repay_id']=($repay_time['repay_id']==1)?3:$repay_time['repay_id'];
                $repay_long = M('SysInstallmentPlan')->where(['id' =>  $repay_time['repay_id'], 'publish' => 1, 'target' => 3])->find();
                M('ConsumeHistory')->where(['id'=>$consume_id])->setField(['repayment_time'=>$repay_time_old+$repay_long['timer']*24*3600,'renew_id'=>$ConsumeHistory['renew_id']+1]);
                M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->setField(['update_time'=>time(),'repayment_time'=>$repay_time_old+$repay_long['timer']*24*3600]);
                Log::info_log("银生宝续借代扣异步通知结果订单号".$consume_id."|用户为|".$customer_id.'|');
                /*** 同时更新续借时间***/
                $CustomerBillPayLogInfo = $CustomerBillPayLog->where(['order_id' => $order_id])->find();
                $key='处理中续借订单-'.$CustomerBillPayLogInfo['consume_id'];
                if($redis->get($key)){
                    $redis_res=$redis->rm($key);
                    /*** 同时更新续借时间***/
                    Log::info_log("易宝续借代扣异步通知结果|订单".$order_id."|删除redis处理中|key:".$key.'|');
                    Log::info_log("易宝续借代扣异步通知结果订单".$order_id."|删除redis处理中的结果|".$redis_res.'|');
                }
                Log::info_log("易宝续借代扣异步通知结果||order_id:".$order_id.'|成功');
            }
        }else{
            $ret_code = '1111';
            Log::info_log("易宝续借代扣异步通知结果||order_id:".$order_id.'|失败');
            $sqldata = array('ret_msg'=>$ret_msg,'ret_code'=>$ret_code);
            $CustomerBillPayLog->where(['order_id'=>$order_id,'pay_time'=>0])->setField($sqldata);
            $CustomerBill = $CustomerBillPayLog->field("customer_id,amount,consume_id")->where(['order_id'=>$order_id])->find();
            $customer_id = $CustomerBill['customer_id'];
            $amount = $CustomerBill['amount'];
            $consumeId = $CustomerBill['consume_id'];
            //预扣金额回滚
            M('Customer')->execute("UPDATE `customer` SET `balance_cash_amount` = `balance_cash_amount` + `balance_prepaid`,`balance_prepaid`=0 where `id` = $customer_id and `balance_prepaid` =$amount");
            $sqldata = array('ret_msg'=>$ret_msg,'ret_code'=>$ret_code);
             /*** ========处理中========***/
            $CustomerBillPayLogInfo = $CustomerBillPayLog->where(['order_id' => $order_id])->find();
            $key='处理中续借订单-'.$CustomerBillPayLogInfo['consume_id'];
            if($redis->get($key)){
                $redis_res=$redis->rm($key);
                Log::info_log("易宝续借代扣异步通知结果|订单".$order_id."|删除redis处理中|key:".$key.'|');
                Log::info_log("易宝续借代扣异步通知结果|订单".$order_id."|删除redis处理中的结果|".$redis_res.'|');
            }
            Log::info_log("易宝续借代扣异步通知结果||order_id:".$order_id.'|失败');
        }
        echo 'SUCCESS';

    }
    ///////////2017年12月5日18:55:43、、、、、、
    /**
     * [getShengAmount 剩余金额计算]
     * @param  [type] $consume_id [description]
     * @return [type]             [description]
     */
    private function  getShengAmount($consume_id){
        $res=D("ConsumeHistory")->field("update_time,part_pay_amount,part_need_pay_amount,consume_amount")->where(['id'=>$consume_id])->find();
        //未还金额=（合同金额-已还金额）*2%*天数+未还金额
        //天数（当前时间-部分还款的时间）
        $res['update_time'] = strtotime(date("Y-m-d 00:00:00",$res['update_time']));
        $overday = (strtotime(date('Y-m-d',time()))-$res['update_time'])/24/60/60;
        if($overday>0){//划扣部分金额逾期的时间
            //本金-已还金额
            $amount=$res['consume_amount']-$res['part_pay_amount'];
            $weihuan=ceil($overday*($amount*Constant::Overdue_Interest_Rate))+Constant::OVER_DATE_RATE+$res['part_need_pay_amount'];
            if(($weihuan+$res['part_pay_amount'])>($res['consume_amount']*2)){
                $shengyu_amount=$res['consume_amount']*2-$res['part_pay_amount'];
            }else{
                $shengyu_amount=$weihuan;
            }
        }else if($overday==0){ //划扣部分金额当天又划扣未还金额，此时只划扣未还金额，不涉及逾期
            $shengyu_amount=$res['part_need_pay_amount']+Constant::OVER_DATE_RATE;
        }else if($res['part_pay_amount']>=$res['consume_amount']){ //已还大于等于合同，直接取剩余金额
            $shengyu_amount=$res['part_need_pay_amount'];
        }
        return  $shengyu_amount;
    }
    ///////////2017年12月5日18:55:43、、、、、、
    /**********************设置银行卡主卡|changeMainCard|找钱花app*******************/
    public  function  changeMainCard(){
        try {
            $customerId = I('post.customer_id', 0, 'int');
            $card_id = I('post.cardNo', '', 'string');
            if (!$card_id || !$customerId) {
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            $userinfo = D('Customer')->has($customerId);
            if (!$userinfo) {
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            $map = array(
                'customer_id' => $customerId,
                'card_num' => $card_id,
            );
            $CustomerBankInfo = M('CustomerBankInfo');
            if (!$CustomerBankInfo->Where($map)->find()) {
                //验证银行卡+用户
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            M('CustomerBankInfo')->startTrans();
            //取消之前的主卡设定
            $cancel_res = M('CustomerBankInfo')->where(['customer_id'=>$customerId])->setField(['is_default'=>0]);
            $set_res = M('CustomerBankInfo')->where($map)->setField(['is_default'=>1]);
            if($cancel_res&&$set_res) {
                M('Finish')->commit();
                $ret = Constant::getReturn(Constant::SUCCESS);

            }else{
                Log::write("------changeMainCard|用户".$customerId."设置银行卡主卡失败------!!!!!!DATABASE ERROR!!!!!!------数据库返回信息：".json_encode($cancel_res).json_encode($set_res), Log::DEBUG);
                M('CustomerBankInfo')->rollback();
                BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
            }

        } catch (BusinessException $e) {
            $this->ajaxReturn(['code' => $e->getCode(), 'msg' => $e->getMessage()]);
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }
    /************融360|选择旧卡支付|设置银行卡主卡|changeMainCard|*************/
    public  function  changeRongBankCard($customerId,$card_id){
        try {
            if (!$card_id || !$customerId) {
                //BusinessException::throwException(Constant::INVALID_PARAMETER);
                //return ['code'=>'201','msg'=>'卡号|客户未设置'];
                Log::rong_write_borrow("***选择已有银行卡|201|客户未设置|用户id：".$customerId."|银行卡卡号：".$card_id);
                // $this->ajaxReturn(['code'=>'400','msg'=>'卡号|客户未设置']);
                return false;
            }
            $userinfo = D('Customer')->has($customerId);
            if (!$userinfo) {
                //BusinessException::throwException(Constant::INVALID_PARAMETER);
                Log::rong_write_borrow("***选择已有银行卡|400|用户不存在|用户id：".$customerId."|银行卡卡号：".$card_id);
                // $this->ajaxReturn(['code'=>'400','msg'=>'卡号|用户不存在']);
                return false;
            }
            $map = array(
                'customer_id' => $customerId,
                'card_num' => $card_id,
            );
            $CustomerBankInfo = M('CustomerBankInfo');
            if (!$CustomerBankInfo->Where($map)->find()) {
                //验证银行卡+用户
                //BusinessException::throwException(Constant::INVALID_PARAMETER);
                Log::rong_write_borrow("***选择已有银行卡|400|卡号错误或用户未绑定过该卡|用户id：".$customerId."|银行卡卡号：".$card_id);
                // $this->ajaxReturn(['code'=>'400','msg'=>'卡号错误或用户未绑定过该卡']);
                return false;
            }
            M('CustomerBankInfo')->startTrans();
            //取消之前的主卡设定
            $cancel_res = M('CustomerBankInfo')->where(['customer_id'=>$customerId])->setField(['is_default'=>0]);
            $set_res = M('CustomerBankInfo')->where($map)->setField(['is_default'=>1]);
            if($cancel_res&&$set_res) {
                M('Finish')->commit();
                $ret = Constant::getReturn(Constant::SUCCESS);

            }else{
                Log::rong_write_borrow("***选择已有银行卡|400|数据库错误，旧卡设置失败|用户id：".$customerId."|银行卡卡号：".$card_id);
                M('CustomerBankInfo')->rollback();
                //BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                // $this->ajaxReturn(['code'=>'400','msg'=>'数据库错误，已有银行卡卡选择失败']);
                return false;
            }

        } catch (BusinessException $e) {
            // $this->ajaxReturn(['code' => $e->getCode(), 'msg' => $e->getMessage()]);
            return false;
        }

        // Response::format($ret);
        //$this->ajaxReturn($ret);
        Log::rong_write_borrow("***选择已有银行卡||用户id：".$customerId."|银行卡卡号：".$card_id.'|返回结果：'.json_encode($ret));
        return true;
    }
    /********************融360|选择旧卡支付|设置银行卡主卡|changeMainCard|*************/
    public  function  changeRongMainCard($customerId,$card_id){
        try {
            if (!$card_id || !$customerId) {
                //BusinessException::throwException(Constant::INVALID_PARAMETER);
                //return ['code'=>'201','msg'=>'卡号|客户未设置'];
                Log::rong_write_borrow("***选择已有银行卡|201|客户未设置|用户id：".$customerId."|银行卡卡号：".$card_id);
                $this->ajaxReturn(['code'=>'400','msg'=>'卡号|客户未设置']);
            }
            $userinfo = D('Customer')->has($customerId);
            if (!$userinfo) {
                //BusinessException::throwException(Constant::INVALID_PARAMETER);
                Log::rong_write_borrow("***选择已有银行卡|400|用户不存在|用户id：".$customerId."|银行卡卡号：".$card_id);
                $this->ajaxReturn(['code'=>'400','msg'=>'卡号|用户不存在']);
            }
            $map = array(
                'customer_id' => $customerId,
                'card_num' => $card_id,
            );
            $CustomerBankInfo = M('CustomerBankInfo');
            if (!$CustomerBankInfo->Where($map)->find()) {
                //验证银行卡+用户
                //BusinessException::throwException(Constant::INVALID_PARAMETER);
                Log::rong_write_borrow("***选择已有银行卡|400|卡号错误或用户未绑定过该卡|用户id：".$customerId."|银行卡卡号：".$card_id);
                $this->ajaxReturn(['code'=>'400','msg'=>'卡号错误或用户未绑定过该卡']);
            }
            M('CustomerBankInfo')->startTrans();
            //取消之前的主卡设定
            $cancel_res = M('CustomerBankInfo')->where(['customer_id'=>$customerId])->setField(['is_default'=>0]);
            $set_res = M('CustomerBankInfo')->where($map)->setField(['is_default'=>1]);
            if($cancel_res&&$set_res) {
                M('Finish')->commit();
                $ret = Constant::getReturn(Constant::SUCCESS);

            }else{
                Log::rong_write_borrow("***选择已有银行卡|400|数据库错误，旧卡设置失败|用户id：".$customerId."|银行卡卡号：".$card_id);
                M('CustomerBankInfo')->rollback();
                //BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                $this->ajaxReturn(['code'=>'400','msg'=>'数据库错误，已有银行卡卡选择失败']);
            }

        } catch (BusinessException $e) {
            $this->ajaxReturn(['code' => $e->getCode(), 'msg' => $e->getMessage()]);
        }

        Response::format($ret);
        //$this->ajaxReturn($ret);
        Log::rong_write_borrow("***选择已有银行卡||用户id：".$customerId."|银行卡卡号：".$card_id.'|返回结果：'.json_encode($ret));
        return $ret;
    }
    /***设置是否可以续借***/
    public  function  setReloan(){
        $consume_id=trim(I('post.consume_id'));//post--.consume_id
        /***增加续借控制***/
        $checkReloan= new Redis();
        //获取该表消费是否可以续借
        $ckReloan=$checkReloan->set('reloan-'.$consume_id);
        Log::info_log('**********设置是否可以续借|setReloan|设置redis-key值|:'.$ckReloan.' ：');

        /***增加续借控制***/
    }
    /***************************
     * 用户续借（续借银生宝代扣）
     ****************************/
    public function NewpayConfirm() {
        try {
            $customerId = I('post.customer_id', 0, 'int');
            $type = I('post.type', 1, 'int'); //类型 1还款 2交首付
            if($type=='') {$type = 1;} //默认还款
            $pay_pass = I('post.pay_pass', '', 'string'); //支付密码(密文)
            $card_num = I('post.card_num', '', 'string'); //用户提交的银行卡
            $consume_id = I('post.consume_id', 0, 'int'); //首付消费ID
            /*** 新版app--amount入参：服务费***/
            $normal_amount = I('post.amount', 0, 'int'); //首付金额,单位分
            /***新版app--amount入参：服务费***/
            $check_pass = I('post.check_pass', 'yes', 'string'); //是否检查密码
            if($check_pass=='') {$check_pass = 'yes';} //是否检查密码默认检查
            $pay_action = I('post.pay_action', 1, 'int'); //还款方式 1用户手动 2系统代扣
            $repay_date = I('post.repay_date', '', 'string'); //最迟还款日
            /*** 续借金额计算***/
            $_overdue_amount_=I('post.overdue_amount');
            /***续借金额计算***/
            //首付金额计算
            $overdue_amount = 0; //首付没有逾期金
            $amount = $normal_amount + $overdue_amount; //实付金额
            $order_type = 2; //首付是按单笔还
            $consume_data_arr = array();
            $consume_data_json = '';
            Log::info_log('NewpayConfirm用户续借 '.$customerId.' 参数：'.json_encode(I('post.')));
            /***续借检查***/
            if($consume_id>0) {
                $repay_time=  M('ConsumeHistory')->where(['id'=>$consume_id])->field('repayment_time,repay_id')->find();
                /***|ConsumeInstallmentHistory新加字段allow_renew控制是否允许展期|默认值为0***/
                $repay_time_=  M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->field('repayment_time,allow_renew')->find();
                //续借日期-->查库---|兼容：产品id为1==>改成3
                $repay_time['repay_id']=($repay_time['repay_id']=='1')?3:$repay_time['repay_id'];
                $repay_long = M('SysInstallmentPlan')->where(['id' =>  $repay_time['repay_id'], 'publish' => 1, 'target' => 3])->find();
                //$repay_long=($repay_time['repay_id']=='1')?30:($repay_time['repay_id']=='2'?14:30);
                $time= time()+$repay_long['timer']*24*3600;
                //续借日期-->查库
                $renew_check=($repay_time_['repayment_time']>$time)?1:0;
                /***续借检查|超出账单周期|暂时不准续借|***/
                $too_long=(time()-$repay_time_['repayment_time']>$repay_long['timer']*24*3600)?1:0;
                /***续借检查|超出账单周期|暂时不准续借|***/
            }
            if($renew_check){
                Log::info_log('NewpayConfirm用户续借 '.$customerId.' 异常 请到期后再续借'.json_encode(I('post.')));
                BusinessException::throwException('请到期后再续借');
            }
            /***续借检查|超出账单周期|暂时不准续借|***/
            if($too_long){
                Log::info_log('NewpayConfirm用户续借 '.$customerId.' 异常 逾期时间太长了~先还款吧亲'.json_encode(I('post.')));
                BusinessException::throwException('逾期时间太长了~先还款吧亲');
            }
            /***续借检查|逾期|暂时不准续借|贷后催收控制是否允许***///if((!$repay_time_['allow_renew'])&&$repay_time_['repayment_time']<time()){
            if((!$repay_time_['allow_renew'])&&($repay_time_['repayment_time']+24*60*60)<time()){
                Log::info_log('NewpayConfirm用户续借 '.$customerId.' 异常 逾期不可续借了'.json_encode(I('post.')));
                BusinessException::throwException('逾期不可续借了~');
            }
            /***续借检查***/
            //还款金额计算
            if($type == 1) {
                $consume_data = I('post.consume_data'); //还款入参
                $consume_data_json = ($consume_data) ? json_encode($consume_data) : '';
                $consume_data_arr = $consume_data;
                if($consume_data_arr) {
                    $consume_data_count = count($consume_data_arr);
                    $order_type = ($consume_data_count >1) ? 1: 2;
                    $normal_amount = 0;
                    $overdue_amount = 0;
                    $overdue_amount_all = 0;
                    foreach($consume_data_arr as $v) {
                        if($v['type']==1) {
                            $normal_amount = $normal_amount + $v['amount'];
                            $overdue_amount_all = $overdue_amount_all + $v['overdue_amount'];
                        }
                        if($v['type']==5) {
                            if($v['installment_history']) {
                                foreach($v['installment_history'] as $v1) {
                                    $normal_amount = $normal_amount + $v1['amount'];
                                    $overdue_amount_all = $overdue_amount_all + $v['overdue_amount']; //逾期金额客户端传值
                                    $this->get_overdue_amount51($v1['id'],$customerId); //逾期情况用户申请额度处理
                                }
                            }
                        }

                        if($v['type']==2 ) {
                            if($v['installment_history']) {
                                $big_id = $v['consume_id'];
                                $small_id = '';
                                foreach($v['installment_history'] as $v1) {
                                    $overdue_amount = $overdue_amount + $v1['overdue_amount'];
                                    $small_id .= $v1['id'].",";
                                }
                                $small_id = substr($small_id, 0, -1);
                                $repay_amount = D('ConsumeHistory')->PaymentCheck($big_id,$small_id); //还款金额外部计算，已包含逾期
                                $normal_amount = $normal_amount + $repay_amount;
                            }
                        }

                    }
                    $amount = $normal_amount + $overdue_amount_all;
                    /*** 续借添加服务费 ***/
                    if($overdue_amount_all){
                        $amount=$amount+Constant::OVER_DATE_RATE;
                    }
                } else {
                    BusinessException::throwException(Constant::INVALID_PARAMETER);
                }
            }
            $pay_type = I('post.paytype', 1, 'int'); //支付方式 1联动优势 2微信APP支付
            if($pay_type=='') {$pay_type = 1;} //默认联动优势
            $userinfo = D('Customer')->has($customerId);
            $mobile = $userinfo['mobile'];
            $mer_date = date('Ymd');
            $order_id = $this->trade_no();
            $balance_amount_old = $userinfo['balance_amount'];
            $balance_cash_amount_old = $userinfo['balance_cash_amount'];
            $credit_level_old = $userinfo['credit_level'];
            /***|打开支付密码校验|***/
            $userData_=M('Customer')->field('id,pay_pass')->where(['id'=>$customerId])->find();
            //验证支付密码
            if (!$userData_['pay_pass']) {
                Log::info_log('+++++++++payConfirm未设置支付密码+++++++++');
                BusinessException::throwException(Constant::UNSET_PAY_PASS);
            }
            if (password_unmatched($pay_pass, $userData_['pay_pass'])) {
                Log::info_log('+++++++++payConfirm支付密码校验失败+++++++++');
                BusinessException::throwException(Constant::PAY_PASS_UNMATCHED);
            }
            //获取用户绑定卡的支付协议号
            $CustomerBankInfo = M('CustomerBankInfo');
            $data_arr = $CustomerBankInfo->where("customer_id = $customerId and sub_contract_id<>''")->field('sub_contract_id')->find();
            /*** 绑定多张银行卡|finishmodel|customerbanckinfo|***/
            Log::info_log("改版过后传过来的银行卡".$card_num);
            // $data_arr = $CustomerBankInfo->where("customer_id = $customerId and sub_contract_id >0 and is_default=1")->field('sub_contract_id,card_user_name')->find();
            $data_arr = $CustomerBankInfo->where(['card_num'=>$card_num,'customer_id'=>$customerId])->field('sub_contract_id,card_user_name')->limit(1)->find();
            /*** 绑定多张银行卡|finishmodel|customerbanckinfo| ****/
            Log::info_log('**********用户续借|银行卡|数据库查询结果：'.json_encode($data_arr).'|');
            /*** 给用户打款操作|本人银行卡校验|***/
            //持卡人姓名：$recv_user_name非系统用户本人
            Log::info_log("*****************newpayConfirm用户真实姓名：".$userinfo['real_name']."|持卡人姓名：".$data_arr['card_user_name']."|*****：");
            if($userinfo['real_name']!=$data_arr['card_user_name']){
                BusinessException::throwException('持卡人必须是本人');
            }
            /*** |续借重复扣款|还款处理中用户|***/
            $redis = new Redis();
            $key='处理中续借订单-'.$consume_id;
            if($redis->get($key)){
                Log::info_log('**********续借订单正在处理中|redis|key：'.$key);
                BusinessException::throwException('续借订单正在处理中');
            }
            /*** 续借重复扣款|还款处理中用户|***/
            /*** 给用户打款操作|本人银行卡校验|***/
            $subContractId = $data_arr['sub_contract_id'];
            if ($subContractId =='') {
                BusinessException::throwException('请先绑定银行卡');
            }
            //还款 入参金额检查
            if ($consume_data_arr && $type==1) {
                foreach($consume_data_arr as $v) {
                    $consume_id = $v['consume_id'];
                    $normal_amount = $v['amount'];
                    $repay_date = $v['repay_date'];
                    $consumeHistory = M('ConsumeHistory')->where(['id' => $consume_id])->find();
                    if (!$consumeHistory) {
                        BusinessException::throwException(Constant::INVALID_PARAMETER);
                    }
                    //费率查询修改
                    $consumeAmount = $consumeHistory['consume_amount']*0.2;
                    //次月
                    if (floatval($consumeHistory['status'])==3) {
                        BusinessException::throwException(Constant::INVALID_PARAMETER);
                    }
                    //分期
                    if($consumeHistory['type']==2  || $consumeHistory['type']==5) {
                        if($v['installment_history']) {
                            $ConsumeInstallmentHistory =D('ConsumeInstallmentHistory');
                            foreach($v['installment_history'] as $v1) {
                                $id = $v1['id'];
                                $normal_amount = floatval($v1['amount']);
                                $repay_date = $v1['repay_date'];
                                $repayment_time = ($repay_date<>'') ? strtotime($repay_date." 00:00:00") : strtotime(date('Y-m-' . Constant::BILL_LAST_DAY . ' 00:00:00', time()));
                                $data_arr = $ConsumeInstallmentHistory->where(['parent_id' => $consume_id,'repayment_time'=>$repayment_time])->field('amount,status')->find();
                                if ($normal_amount != $data_arr['amount'] && $data_arr['amount']>0) {
                                    BusinessException::throwException(Constant::INVALID_PARAMETER);
                                }
                                if ($data_arr['status']==1) {
                                    BusinessException::throwException(Constant::INVALID_PARAMETER);
                                }
                            }
                        }
                    }
                }
                //还多笔
                if($order_type==1) {
                    $consume_id = 0;
                    $repay_date = '';
                }
            }
            if ($amount==0) {
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            $CustomerBillPayLog = M('CustomerBillPayLog');
            //入库
            $data = array(
                'order_id' => $order_id,
                'order_type' => $order_type,
                'customer_id' => $customerId,
                'consume_id' => $consume_id,
                'consume_data' => $consume_data_json,
                'repay_date' => $repay_date,
                'amount' => $amount,
                'trade_id' => '',
                'pay_type' => $pay_type,
                'type' => $type,
                'balance_amount_old' =>$balance_amount_old,
                'balance_cash_amount_old' =>$balance_cash_amount_old,
                'overdue_amount' => $overdue_amount,
                'pay_action' => $pay_action,
            );
            if (false === ($insertId = $CustomerBillPayLog->add($data))) {
                BusinessException::throwException('支付订单创建失败');
            }

            if ($customerId == "2162"){
                $uns_amount = 400.00 ;//测试写死1分钱
            }else {
                $uns_amount = $amount * 0.01;
            }
            Log::info_log('续借用户：'.$customerId.' '.' '.$uns_amount.' '.$order_id.'  '.$card_num);
            //$result = $this->NewunsPay($subContractId,$order_id,$uns_amount);
            $result= $this->yibaoNewPay($customerId,$card_num,$uns_amount,$order_id);
            Log::info_log('续借用户'.$customerId.' 续借执行结果： '.json_encode($result));
            if($result) {
                $ret_code ='0000';
                $ret_msg = '';
                $trade_state = '0000';//$result['status']
                if($ret_code=='0000') {
                    //$resultstatu = $this->unsPaystatu($order_id);
                    $yborderid='';
                    $resultstatu =D('Yibao')->yibaoSearch($order_id,$yborderid);
                    /*查询是否扣款成功*/
                    Log::info_log("易宝渠道查询续借-".' '.$customerId.'    '.$card_num.'     '.$uns_amount.'      '.$order_id.'   返回'.$resultstatu.json_encode($resultstatu));
                    if($resultstatu['status'] == 'PAY_SUCCESS'){
                        //还款成功写库
                        $sqldata = array('trade_state'=>$trade_state,'ret_msg'=>'success','pay_time'=>time(),'ret_code'=>$ret_code,'status'=>1);
                        $test1=$CustomerBillPayLog->where(['id'=>$insertId,'status'=>0])->setField($sqldata);
                        Log::info_log('续借用户'.$customerId.'实际还款成功入库 CustomerBillPayLog:结果'.json_encode($test1));
                        $CustomerBillPayLogInfo = $CustomerBillPayLog->where(['order_id' => $order_id])->find();
                        $consume_id = $CustomerBillPayLogInfo['consume_id'];
                        $customer_id = $CustomerBillPayLogInfo['customer_id'];
                        $ConsumeHistory = M('consume_history')->where(['id' => $consume_id])->find();
                        Log::info_log('续借用户 '.$customerId.'实际还款成功入库 consume_id 结果'.$consume_id);
                        if($consume_id>0) {
                            /****这里扣款成功修改status给贷后分单用，防止撤单分单出现已还款仍能撤分单***/
                            $ConsumeUserInfo = M('consume_user')->where("consume_id = $consume_id and status = 1")->find();
                            if (isset($ConsumeUserInfo) && !empty($ConsumeUserInfo)) {
                                $ConsumeUserStatusInfo = M('consume_user')->where("consume_id = $consume_id and status = 1")->setField(array('status'=>3));//状态3表示逾期续借
                            }
                            /****这里扣款成功修改status给贷后分单用，防止撤单分单出现已还款仍能撤分单***/
                            $repay_time=  M('ConsumeHistory')->where(['id'=>$consume_id])->field('repayment_time,repay_id')->find();
                            $repay_time_=  M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->field('repayment_time')->find();

                            //之前还款时间
                            $repay_time_old=$repay_time_['repayment_time'];
                            if(!$repay_time_old){//如果不存在|默认取当前当前
                                $repay_time_old=time();
                            }
                            //根据用户选择的产品|延迟天数--查库
                            //$repay_long=($repay_time['repay_id']=='1')?30:($repay_time['repay_id']=='2'?14:30);
                            $repay_time['repay_id']=($repay_time['repay_id']==1)?3:$repay_time['repay_id'];
                            $repay_long = M('SysInstallmentPlan')->where(['id' =>  $repay_time['repay_id'], 'publish' => 1, 'target' => 3])->find();
                            $test4=M('Customer')->where(['id'=>$customer_id])->setField(['balance_cash_amount'=>$uns_amount]);
                            /***|该次展期成功|展期控制状态归0|***/
                            M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->setField(['allow_renew'=>0]);
                            Log::info_log('续借用户'.$customerId.'实际还款成功入库 ConsumeHistory:'.json_encode($test2).'|ConsumeInstallmentHistory结果：'.json_encode($test3).'|Customer结果：'.json_encode($test4));
                            $res = M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->field("repayment_time,add_time,amount")->order("id DESC")->limit(1)->find();
                            $getrepaytimer = M('SysInstallmentPlan')->where(['id'=>$repay_time['repay_id']])->field('timer')->find();
                            $repayment_time = date("Y-m-d",$res['repayment_time']);
                            $add_time = date("Y-m-d",$res['add_time']);
                        }
                        $ret = Constant::getReturn(Constant::SUCCESS);
                        $ret['data'] = array('order_id'=>$order_id,'repayment_time'=>$repayment_time,'add_time'=>$add_time,'timer'=>$getrepaytimer['timer'],'amount'=>$res['amount']);
                        /*查询是否扣款成功*/
                    }else if($resultstatu['status'] == 'PAY_FAIL'){
                        $status = 3;
                        $sqldata = array('ret_msg'=>$resultstatu['errormsg'],'ret_code'=>1111,'status'=>$status);
                        $CustomerBillPayLog->where(['id'=>$insertId,'status'=>0])->setField($sqldata);
                        //手动输入的预扣金额为零
                        M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id,'update_time'=>0])->setField(["final_amount"=>0]);
                        $this->ajaxReturn(['code' => 1111, 'msg' => '银行卡上余额不足']);
                    }elseif($resultstatu['status'] == 'PROCESSING'){
                        /*** 续借订单处理中|订单***/
                        $key='处理中续借订单-'.$consume_id;
                        $redis_res=$redis->set($key,'10',1800);
                        Log::info_log('续借用户  订单号码：'.$order_id.' 查询用户是否实际还款返回结果 存入redis结果 '.json_encode($redis_res));
                        $this->ajaxReturn(['code' => 10, 'msg' =>$resultstatu['errormsg']]);
                    }


                } else {
                    //付款提交失败
                    $status = 3;
                    $sqldata = array('ret_msg'=>$trade_state,'ret_code'=>$ret_code,'status'=>$status);
                    $CustomerBillPayLog->where(['id'=>$insertId,'status'=>0])->setField($sqldata);
                    Log::info_log('用户 续借 订单号码：'.$order_id.'  续借失败');
                    //手动输入的预扣金额为零
                    M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id,'update_time'=>0])->setField(["final_amount"=>0]);
                    BusinessException::throwException($ret_code.$trade_state);
                }
            }

        } catch (BusinessException $e) {
            Log::info_log(' 用户'.$customerId.'续借错误 异常code：'.$e->getCode().'|异常msg:'.$e->getMessage());
            //$this->ajaxReturn(['code' => $e->getCode(), 'msg' => $e->getMessage(),'data'=>['amount'=>$amount,'customerId'=>$customerId]]);
            $ret=['code' => $e->getCode(), 'msg' => $e->getMessage(),'data'=>['amount'=>$amount,'customerId'=>$customerId]];
        }

        Response::format($ret);
        Log::info_log(' 续借用户'.$customerId.'返回前台数据：'.json_encode($ret));
        $this->ajaxReturn($ret);
    }


    //51用户还款（线下还款）
    public function pay51Confirm() {

        try {
            $customerId = I('post.customer_id', 0, 'int');
            //$amount = I('post.amount', 0, 'int'); //所还本金金额,单位分

            $type = I('post.type', 1, 'int'); //类型 1还款 2交首付
            if($type=='') {$type = 1;} //默认还款

            $pay_pass = I('post.pay_pass', '', 'string'); //支付密码(密文)
            $consume_id = I('post.consume_id', 0, 'int'); //首付消费ID
            $normal_amount = I('post.amount', 0, 'int'); //首付金额,单位分

            $repay_date = I('post.repay_date', '', 'string'); //最迟还款日
            //$overdue_amount = I('post.overdue_amount', 0, 'int'); //所还逾期金额,单位分

            //首付金额计算
            $overdue_amount = 0; //首付没有逾期金
            $amount = $normal_amount + $overdue_amount; //实付金额

            $order_type = 2; //首付是按单笔还
            $consume_data_arr = array();
            $consume_data_json = '';
            //还款金额计算
            if($type == 1) {
                $consume_data = I('post.consume_data'); //还款入参
                //$consume_data_arr = json_decode($consume_data,true);
                $consume_data_json = ($consume_data) ? json_encode($consume_data) : '';
                $consume_data_arr = $consume_data;
                if($consume_data_arr) {
                    $consume_data_count = count($consume_data_arr);
                    $order_type = ($consume_data_count >1) ? 1: 2;
                    // {"consume_id":"11","repay_date":"2016-10-10","amount":"还款金额，单位：分","overdue_amount":"所还逾期金额,单位分"}
                    $normal_amount = 0;
                    $overdue_amount = 0;
                    foreach($consume_data_arr as $v) {
                        if($v['type']==1) {
                            $normal_amount = $normal_amount + $v['amount'];
                            $overdue_amount = $overdue_amount + $v['overdue_amount'];
                        }

                        if($v['type']==2 || $v['type']==5) {
                            if($v['installment_history']) {
                                foreach($v['installment_history'] as $v1) {
                                    $normal_amount = $normal_amount + $v1['amount'];
                                    $overdue_amount = $overdue_amount + $v1['overdue_amount'];
                                }
                            }
                        }
                    }
                    $amount = $normal_amount + $overdue_amount;
                } else {
                    BusinessException::throwException(Constant::INVALID_PARAMETER);
                }
            }

            $pay_type = I('post.paytype', 1, 'int'); //支付方式 1联动优势 2微信APP支付
            if($pay_type=='') {$pay_type = 1;} //默认联动优势

            $userinfo = D('Customer')->has($customerId);
            $mobile = $userinfo['mobile'];
            $mer_date = date('Ymd');
            $order_id = $this->trade_no();
            $balance_amount_old = $userinfo['balance_amount'];
            $balance_cash_amount_old = $userinfo['balance_cash_amount'];
            $credit_level_old = $userinfo['credit_level'];
            //验证支付密码
            /*
            $encPayPass = M('Customer')->where(['id' => $customerId])->getField('pay_pass');
            if (!$encPayPass) {
                BusinessException::throwException(Constant::UNSET_PAY_PASS);
            }
            */
            /*
            if (password_unmatched($pay_pass, $encPayPass)) {
                BusinessException::throwException(Constant::PAY_PASS_UNMATCHED);
            }
            */
            /*
            if ($pay_pass<>'518E6C76CAF51EB410CAAB3C21DEF1B4B3C07401') {
                BusinessException::throwException(Constant::PAY_PASS_UNMATCHED);
            }*/


            //获取用户绑定卡的支付协议号
            $CustomerBankInfo = M('CustomerBankInfo');
            $data_arr = $CustomerBankInfo->where(['customer_id' => $customerId])->field('usr_pay_agreement_id')->find();
            $usr_pay_agreement_id = $data_arr['usr_pay_agreement_id'];

            //首付参数检查
            if ($consume_id && $type==2) {
                $consumeHistory = M('ConsumeHistory')->where(['id' => $consume_id])->find();
                if (!$consumeHistory) {
                    BusinessException::throwException(Constant::INVALID_PARAMETER);
                }

                //首付 入参金额检查
                if ($normal_amount != $consumeHistory['down_payment'] && $consumeHistory['down_payment']>0) {
                    BusinessException::throwException(Constant::INVALID_PARAMETER);
                }
            }

            //还款 入参金额检查
            if ($consume_data_arr && $type==1) {
                foreach($consume_data_arr as $v) {
                    $consume_id = $v['consume_id'];
                    $normal_amount = $v['amount'];
                    $repay_date = $v['repay_date'];
                    $consumeHistory = M('ConsumeHistory')->where(['id' => $consume_id])->find();
                    if (!$consumeHistory) {
                        BusinessException::throwException(Constant::INVALID_PARAMETER);
                    }

                    //次月
                    if ($normal_amount != $consumeHistory['amount'] && $consumeHistory['type']==1) {
                        BusinessException::throwException(Constant::INVALID_PARAMETER);
                    }
                    //分期
                    if($consumeHistory['type']==2  || $consumeHistory['type']==5) {
                        if($v['installment_history']) {
                            $ConsumeInstallmentHistory =D('ConsumeInstallmentHistory');
                            foreach($v['installment_history'] as $v1) {
                                $id = $v1['id'];
                                $normal_amount = $v1['amount'];
                                $repay_date = $v1['repay_date'];
                                //$repayment_time = strtotime(date('Y-m-' . Constant::BILL_LAST_DAY . ' 00:00:00', time()));
                                $repayment_time = ($repay_date<>'') ? strtotime($repay_date." 00:00:00") : strtotime(date('Y-m-' . Constant::BILL_LAST_DAY . ' 00:00:00', time()));
                                $data_arr = $ConsumeInstallmentHistory->where(['parent_id' => $consume_id,'repayment_time'=>$repayment_time])->field('amount')->find();
                                if ($normal_amount != $data_arr['amount'] && $data_arr['amount']>0) {
                                    BusinessException::throwException(Constant::INVALID_PARAMETER);
                                }
                            }
                        }
                    }
                }
                //还多笔
                if($order_type==1) {
                    $consume_id = 0;
                    $repay_date = '';
                }
            }

            if ($amount==0) {
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            $CustomerBillPayLog = M('CustomerBillPayLog');

            $url = true;
            if($url) {

                $ret_code1 = '0000';
                if($ret_code1=='0000') {
                    $trade_no = '';

                    //入库
                    $data = array(
                        'order_id' => $order_id,
                        'order_type' => $order_type,
                        'customer_id' => $customerId,
                        'consume_id' => $consume_id,
                        'consume_data' => $consume_data_json,
                        'repay_date' => $repay_date,
                        'amount' => $amount,
                        'trade_id' => $trade_no,
                        'pay_type' => $pay_type,
                        'type' => $type,
                        'balance_amount_old' =>$balance_amount_old,
                        'balance_cash_amount_old' =>$balance_cash_amount_old,
                        'overdue_amount' => $overdue_amount
                    );
                    if (false === ($insertId = $CustomerBillPayLog->add($data))) {
                        BusinessException::throwException('支付订单创建失败');
                    }

                    if($url) {
                        $ret_code2 = '0000';
                        if($ret_code2=='0000') {
                            //还款成功写库
                            $pay_time51 = time();
                            $sqldata = array('trade_state'=>$trade_state,'ret_code'=>$ret_code2,'status'=>1,'ret_msg'=>'success','pay_time'=>$pay_time51);
                            $CustomerBillPayLog->where(['id'=>$insertId,'status'=>0])->setField($sqldata);

                            //更新用户账单和消费数据状态
                            $this->updateUserData($amount,$normal_amount,$overdue_amount,$customerId,$consume_id,$repay_date,$balance_amount_old,$balance_cash_amount_old,$insertId,$type,$consume_data_arr,$credit_level_old);

                            //$order_id = $data->H_table['order_id'];
                            $ret = Constant::getReturn(Constant::SUCCESS);
                            $ret['data'] = array('order_id'=>$order_id);
                        } else {
                            //付款失败
                            if($ret_code2=='00200014') {
                                $status = 2; //支付结果不明
                            } else {
                                $status = 3;
                            }
                            $sqldata = array('ret_msg'=>$ret_msg2,'ret_code'=>$ret_code2,'status'=>$status);
                            $CustomerBillPayLog->where(['id'=>$insertId,'status'=>0])->setField($sqldata);

                            BusinessException::throwException($ret_code2.$ret_msg2);
                        }
                    }

                } else {
                    BusinessException::throwException($ret_code1.$ret_msg1);
                }
            }

        } catch (BusinessException $e) {
            $this->ajaxReturn(['code' => $e->getCode(), 'msg' => $e->getMessage()]);
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }
    //还款成功更新用户数据 作废
    private function updateUserData($amount,$normal_amount,$overdue_amount,$customerId,$consume_id,$repay_date,$balance_amount_old,$balance_cash_amount_old,$insertId,$type,$consume_data_arr,$credit_level_old) {

        $CustomerBill =M('CustomerBill');
        $ConsumeHistory =M('ConsumeHistory');
        $ConsumeInstallmentHistory =D('ConsumeInstallmentHistory');
        $Customer = M('Customer');

        //更新用户账单和消费记录
        if($type ==2) {
            //交首付
            //修改账单状态
            $ConsumeHistory->execute("UPDATE `consume_history` SET `status`='8'  WHERE `status` ='2' AND `customer_id` = '$customerId' and `id`='$consume_id'");
            try{
                //参数校验
                Log::write("[start][orderRealPay][consume_id=".$consume_id."]:开始执行", Log::INFO);
                if(!$consume_id){
                    BusinessException::throwException(Constant::INVALID_PARAMETER);
                }
                //开启事务
                M('Finish')->startTrans();
                D('Finish')->OrderFinish($consume_id);
                $ret = Constant::getReturn(Constant::SUCCESS);

            }catch (BusinessException $e){
                M('Finish')->rollback();
            }
            Log::write("[end][orderRealPay][consume_id=".json_encode($ret, JSON_UNESCAPED_UNICODE)."]:执行结束", Log::INFO);
            M('Finish')->commit();

        } elseif($type ==1) {
            //还款
            //这个版本，次月还款和分期还款不能混在一次一次性还清
            foreach($consume_data_arr as $v) {
                $consume_type = $v['type'];
            }
            //消费次月
            if($consume_type==1) {
                $normal_amount_all = 0;
                foreach($consume_data_arr as $v) {
                    $consume_id = $v['consume_id'];
                    $data_arr = $ConsumeHistory->where(['id' => $consume_id])->field('type,repayment_time,amount')->find();
                    //$consume_type = $data_arr['type'];
                    $repayment_time = $data_arr['repayment_time'];
                    //次月还款
                    /*
                                        //还某次消费的欠款
                                        //$CustomerBill->execute("UPDATE `customer_bill` SET `status`='1',`update_time`='".time()."',`paid`=`repayment_amount` WHERE `status` = 0 AND `customer_id` = '".$customerId."' and `id`='".$consume_id."'");
                                        //$ConsumeHistory->where(['id'=>$consume_id,'status'=>array('neq',3),'customer_id'=>$customerId])->setField(['status'=>3,'update_time'=>time());
                                        //本月还上个月
                                        //$bill_date_last = $this->GetMonth();
                    */
                    $normal_amount = $v['amount'];//还款金额（次月不含利息）
                    $overdue_amount = $v['overdue_amount']; //逾期金额
                    $bill_date_last = date('Y-m');
                    $CustomerBill->execute("UPDATE `customer_bill` SET `update_time`='".time()."',`status` = 1,`repayment_amount`=`repayment_amount`-$normal_amount ,`paid`=`paid`+ $normal_amount WHERE  `customer_id` = '$customerId' and `type`='1' and `bill_date`='$bill_date_last' and `repayment_amount`>=$normal_amount");
                    //修改账单状态
                    $ConsumeHistory->execute("UPDATE `consume_history` SET `status`='3',`update_time`='".time()."',`overdue_amount`='$overdue_amount' WHERE `status` <>3 AND `customer_id` = '$customerId' and `id`='$consume_id'");

                    $normal_amount_all = $normal_amount_all + $normal_amount; //循环累加
                }//foreach end

                if($normal_amount_all>0) {
                    //修改还款记录表本金字段
                    $Customer->execute("UPDATE `customer_bill_pay_log` SET `normal_amount`= $normal_amount_all WHERE  `id` = '$insertId'");
                    //增加可用金额（次月没有利息）
                    $Customer->execute("UPDATE `customer` SET `balance_amount`=`balance_amount` + $normal_amount_all WHERE  `id` = '$customerId' and `balance_amount`='$balance_amount_old'");
                }
            }
            //分期还款（包括消费分期和现金贷分期）
            if($consume_type==2 || $consume_type==5) {
                $normal_amount_all =0;
                $amount_history_all = 0;
                foreach($consume_data_arr as $v) {

                    $consume_id = $v['consume_id'];
                    $consume_result_arr = $ConsumeHistory->where(['id' => $consume_id])->field('type,repayment_time,amount,consume_amount')->find();
                    //$consume_type = $data_arr['type'];
                    if($consume_type==2) {
                        $consume_amount = $consume_result_arr['amount'];
                    }
                    if($consume_type==5) {
                        $consume_amount = $consume_result_arr['consume_amount'];
                    }
                    if($v['installment_history']) {
                        $ConsumeInstallmentHistory =D('ConsumeInstallmentHistory');
                        //分期期数，默认10期
                        $installment_num_arr = $ConsumeInstallmentHistory->where(['parent_id' => $consume_id])->field('id')->select();
                        $installment_num = ($installment_num_arr) ? count($installment_num_arr) : 10;
                        $amount_history = ceil($consume_amount/$installment_num); //还款金额（不包含利息）

                        foreach($v['installment_history'] as $v1) {

                            $normal_amount = $v1['amount'];//还款金额（分期含利息）
                            $overdue_amount = $v1['overdue_amount']; //逾期金额
                            $bill_date_last = date('Y-m');
                            $repay_date = $v1['repay_date'];

                            //还某次消费的欠款
                            //$bill_date_last = $this->GetMonth();
                            $bill_date_last = date('Y-m');
                            $CustomerBill->execute("UPDATE `customer_bill` SET `update_time`='".time()."',`repayment_amount`=`repayment_amount`-$normal_amount ,`paid`=`paid`+ $normal_amount,`status`=1 WHERE  `customer_id` = '$customerId' and `type`='2' and `bill_date`='$bill_date_last' and `repayment_amount`>=$normal_amount");

                            /*
                                                        //计算当前的还款账单时间
                                                        //$repayment_time = strtotime('2016-09-10');
                                                        //bug 之前的函数计算有误
                                                        //$data = array('repayment_time'=>$repayment_time);
                                                        //$repayTime = $ConsumeInstallmentHistory->getRepaymentTime($data);

                                                        //修改当前分期账单状态，每月1号重新置为未还，而且要修改repayment_time(分期的status不这样改了)
                                                        //$ConsumeHistory->execute("UPDATE `consume_history` SET `update_time`='".time()."' WHERE `status` <>3 AND `customer_id` = '$customerId' and `id`='$consume_id'");
                            */
                            //本月最后还款日期的订单（还款时间1号~10号）
                            $repayment_time = ($repay_date<>'') ? strtotime($repay_date." 00:00:00") : strtotime(date('Y-m-' . Constant::BILL_LAST_DAY . ' 00:00:00', time()));
                            $parent_id = $consume_id;
                            $ConsumeInstallmentHistory->execute("UPDATE `consume_installment_history` SET `status`='1',`update_time`='".time()."',`overdue_amount`='$overdue_amount' WHERE `status`=0 AND `parent_id`='$parent_id' and `repayment_time`='$repayment_time'");

                            $data_arr = $ConsumeInstallmentHistory->where(['parent_id' => $parent_id])->field('status')->select();
                            if($data_arr) {
                                $consume_status = 1;
                                foreach($data_arr as $v) {
                                    if($v['status']==0) {
                                        $consume_status = 0;
                                        break;
                                    }
                                }
                                if($consume_status) {
                                    $ConsumeHistory->execute("UPDATE `consume_history` SET `status`='3',`update_time`='".time()."' WHERE `status` <>3 AND `customer_id` = '$customerId' and `id`='$consume_id'");
                                }
                            }
                            $amount_history_all = $amount_history_all + $amount_history;
                        }//foreach end
                        //更新消费记录的最后还款日期（bug 自然月还款）
                        $repayment_time_arr = $ConsumeInstallmentHistory->query("select `repayment_time` from `consume_installment_history` WHERE `status`='0' and `parent_id`='$parent_id' order by `repayment_time` asc limit 1");
                        //$repayment_time_next = strtotime(date($this->GetMonth(0) .'-'. Constant::BILL_LAST_DAY . ' 00:00:00', time()));
                        $repayment_time_next = ($repayment_time_arr) ? $repayment_time_arr[0]['repayment_time'] : 0;
                        $ConsumeHistory->execute("UPDATE `consume_history` SET `repayment_time`='$repayment_time_next' WHERE  `customer_id` = '$customerId' and `id`='$consume_id'");
                    }
                }//foreach end
                if($amount_history_all > 0) {
                    //修改还款记录表本金字段
                    $Customer->execute("UPDATE `customer_bill_pay_log` SET `normal_amount`= $amount_history_all WHERE  `id` = '$insertId'");
                    if($consume_type==5) {
                        //增加可用金额（只加本金不算利息）
                        $Customer->execute("UPDATE `customer` SET `balance_cash_amount`=`balance_cash_amount` + $amount_history_all  WHERE  `id` = '$customerId' and `balance_cash_amount`='$balance_cash_amount_old'");

                        //还款后增加信用级别
                        $Customer->execute("UPDATE `customer` SET `credit_level`= `credit_level` +1  WHERE  `id` = '$customerId' and `credit_level`='$credit_level_old'");

                        //还款后发push
                        $xml_data = array(
                            "msg_type"=>"6",
                            "customer_id" => $customerId,
                        );
                        $sign = $this->genSign($xml_data);
                        $url = $this->unsResponseHost."/Home/JPush/commonPush";
                        $xml_data['sign'] = $sign;
                        $this->curlPost($url,$xml_data);

                    }
                    if($consume_type==2) {
                        //增加可用金额（只加本金不算利息）
                        $Customer->execute("UPDATE `customer` SET `balance_amount`=`balance_amount` + $amount_history_all  WHERE  `id` = '$customerId' and `balance_amount`='$balance_amount_old'");
                    }
                }
            }
        }
    }

    //决策
    public function userDecision($token,$customerId) {
        /*
        1.姓名、手机、身份证、绑卡成功。
        2. 运营商时间大于5个月，通话数量大于100个号码，
        3.通讯录联系人大于100人  ;
        4. 运营商最常联系前20个号码，大于10个在通讯录中;
        */
        //$token = '1fe0b33a2a9d4082bc0d4cab19999d83';
        //$customerId = 97824;
        $userinfo = D('Customer')->has($customerId);
        $real_name = $userinfo['real_name']; //用户姓名
        $id_num = $userinfo['id_num'];//用户身份证

        $CustomerBankInfo = M('CustomerBankInfo')->where("customer_id = $customerId and sub_contract_id<>''")->find();
        $customercontactinfo =  M('CustomerContact')->where(['customer_id' => $customerId ])->field('contact_phone')->group('contact_phone')->select();
        //print_r($customercontactinfo);
        $customer_contact_phone_arr = [];//用户通讯录里电话号码
        if($customercontactinfo) {
            foreach($customercontactinfo as $k=>$v) {
                $customer_contact_phone_arr[] = trim(str_replace('-','',str_replace('+86','',$v['contact_phone'])));
            }
        }
        $customer_contact_phone_arr_count = count($customer_contact_phone_arr); //用户通讯录数量

        $DHBReport_json = file_get_contents($this->unsResponseHost."/Home/Hulushuju/getReport?token=$token");
        if($DHBReport_json) {
            $DHBReport_arr = json_decode($DHBReport_json,true);
            if($DHBReport_arr['code_description']=="DATA_REPORT_ACCESS_SUCCESS") {
                $dhb_real_name = $DHBReport_arr['data']['person']['real_name'];
                $dhb_id_card_num = $DHBReport_arr['data']['person']['id_card_num'];

                $dhb_cell_behavior_month_count = count($DHBReport_arr['data']['cell_behavior'][0]['behavior']); //运营商使用月份
                $dhb_cell_behavior_call_phone_num_count = count($DHBReport_arr['data']['contact_list']); //运营商通话号码数

                if($DHBReport_arr['data']['contact_list']) {
                    $call_phone_num_max20_arr = [];
                    $call_phone_num_arr_desc =$this->my_array_multisort($DHBReport_arr['data']['contact_list'],'call_cnt',SORT_DESC);
                    $i=0;
                    foreach($call_phone_num_arr_desc as $v) {
                        if($i<20) {
                            $call_phone_num_max20_arr[] = $v['phone_num']; //运营商最常联系前20个号码
                        }
                        $i++;
                    }
                }

                //echo '<pre>';
                //print_r($call_phone_num_max20_arr);
                //$dhb_behavior_check =
                $in_max_num =0;
                if($call_phone_num_max20_arr) {
                    foreach($call_phone_num_max20_arr as $v) {
                        if(in_array($v,$customer_contact_phone_arr)) {
                            $in_max_num++; //运营商最常联系前20个号码,在通讯录中的数量
                        }
                    }
                }
            } else {
                D()->execute("UPDATE `customer` SET `decision_status`='-1'  WHERE  `id` = '$customerId'");
                return -1;
            }
        } else {
            D()->execute("UPDATE `customer` SET `decision_status`='-1'  WHERE  `id` = '$customerId'");
            return -1;
        }
        $resultA = ($dhb_real_name == $real_name && $dhb_id_card_num== $id_num) ? 1 : 0; //身份证姓名和运营商信息匹配
        $resultB = ($CustomerBankInfo) ? 1 : 0; //绑卡成功
        $resultC =($customer_contact_phone_arr_count>50 ) ? 1 : 0; //通讯录联系人大于100人  ;
        $resultD =($dhb_cell_behavior_month_count>=5) ? 1 : 0; //运营商时间大于5个月，
        $resultE =($dhb_cell_behavior_call_phone_num_count>=50) ? 1 : 0; //通话数量大于100个号码，
        $resultF =($in_max_num>=10) ? 1 : 0; //运营商最常联系前20个号码，大于10个在通讯录中;
        //echo "A".$resultA.' B'.$resultB.' C'.$resultC.' D'.$resultD.' E'.$resultE.' F'.$resultF;
        $decision_result = "A".$resultA.' B'.$resultB.' C'.$resultC.' D'.$resultD.' E'.$resultE.' F'.$resultF;
        $result =D()->execute("UPDATE `customer` SET `decision_result`='$decision_result'  WHERE  `id` = '$customerId'");

        return ($resultA&&$resultB&&$resultC&&$resultD&&$resultE&&$resultF);
    }
    //多维数组排序
    function my_array_multisort($data,$sort_order_field,$sort_order=SORT_ASC,$sort_type=SORT_NUMERIC){
        foreach($data as $val){
            $key_arrays[]=$val[$sort_order_field];
        }
        array_multisort($key_arrays,$sort_order,SORT_NUMERIC,$data);
        return $data;
    }
    //审核通过，打电话，异步执行
    public function orderCheckPass() {
        try {
            //$consumeId = I('post.consume_id', 0, 'int');
            $consumeId = $_GET['id'];
            $consumeinfo =  M('ConsumeHistory')->where(['id' => $consumeId ])->find();
            $customerId = $consumeinfo['customer_id'];
            $userinfo = D('Customer')->has($customerId);
            $user_decision = $userinfo['decision_result'];
            $user_decision_status = $userinfo['decision_status'];

            if($user_decision_status==2) {
                BusinessException::throwException('决策执行失败');
            }
            //决策
            if($user_decision_status==0 || $user_decision_status==-1) {
                $token = '';
                $customer_auth_info =  M('CustomerAuth')->where("`customer_id`='$customerId' and `china_mobile`=1 and `token`<>''")->field('token')->find();
                if($customer_auth_info) {
                    $token = $customer_auth_info['token'];
                }
                $result =D()->execute("UPDATE `customer` SET `decision_consume`='$consumeId'  WHERE  `id` = '$customerId'");
                if($token<>'' && $customerId>0) {
                    //决策
                    $decision_result = $this->userDecision($token,$customerId);
                    if($decision_result==0) {
                        $result =D()->execute("UPDATE `consume_history` SET `status`=7  WHERE  `id` = '$consumeId'");
                        $result =D()->execute("UPDATE `customer` SET `decision_status`='2'  WHERE  `id` = '$customerId'");
                        BusinessException::throwException('决策执行失败');
                    } elseif($decision_result==1) {
                        $result =D()->execute("UPDATE `customer` SET `decision_status`='1'  WHERE  `id` = '$customerId'");
                    } elseif($decision_result==-1) {
                        BusinessException::throwException('未获取运营商报告');
                    }
                } else {
                    BusinessException::throwException('运营商认证失败');
                }
            }
            $tel = $userinfo['mobile'];
            $name = $userinfo['real_name'];
            $repay_id = $consumeinfo['repay_id'];
            $repayinfo =  M('SysInstallmentPlan')->where(['id' => $repay_id ])->find();

            //$repaymentDays = ($consumeinfo['repayment_time']>0) ? $consumeinfo['repayment_time'] : (time() + $repayinfo['timer']*24*3600);
            $repaymentDays = (time() + $repayinfo['timer']*24*3600);
            //Log::write("润天记录入库22:".$consumeinfo['repayment_time'].'  '.$repaymentDays, Log::INFO);
            $repaymentDay = date('Y年m月d日',$repaymentDays); //还款日 repayment_time
            $actualDay =$repayinfo['timer']; //借款期限
            $idcard = substr($userinfo['id_num'],-4); //身份证号后4位
            $orderId = $consumeId; //消费账单ID
            $userId = $customerId;
            $arrivalAmount = floor($consumeinfo['amount']/100); //到账金额（砍头息）
            $actualNum = floor($consumeinfo['consume_amount']/100); //借款金额
            $repaymentNum = ($repayinfo['interest_rate']<>'') ? $actualNum + $actualNum * $repayinfo['interest_rate'] : 0.01; //还款金额（包含利息）

            //BusinessException::throwException(201,'运营的');
            $result =D()->execute("UPDATE `consume_history` SET `type`=5,`status`=12  WHERE  `id` = '$consumeId' and `type`=4 and `status`=5");
            //1个手机号可以呼多次，在任务里控制
            //$result  = true;
            if($result) {
                $data = array(
                    'tel' => $tel,
                    'repayment_day' => date('Y-m-d',$repaymentDays),
                    'arrival_amount' =>$arrivalAmount,
                    'repayment_num' => $repaymentNum,
                    'actual_num' => $actualNum,
                    'actual_day' => $actualDay,
                    'idcard' => $idcard,
                    'name' => $name,
                    'order_id' => $consumeId,
                    'user_id' => $customerId,
                    'user_field' => '',
                    'status' => 0,
                );
                Log::write("润天记录入库:".json_encode($data), Log::INFO);
                $insertId = M('UserVlink')->add($data);
                D()->execute("UPDATE `user_vlink` SET `user_field`= '$insertId' WHERE  `id` = '$insertId'");

                $data = array(
                    'data_id' => $insertId,
                    'data_type' => 1,
                    'data_action' =>0,
                    'add_time' => time(),
                    'status' => 0,
                );
                M('SystemTasks')->add($data);

                //请求 转计划任务发送
                /*
                $time = time();
                $sign = md5('xxxxxx'.'xxxxxxxxxxxxxxxxxxxxxx'.$time);
                Log::write("润天请求:"."http://api.vlink.cn/interface/open/v1/CallAndSave?appId=xxxxxx&tel=$tel&timestamp=$time&sign=$sign&repaymentDay=$repaymentDay&arrivalAmount=$arrivalAmount&orderId=$orderId&idcard=$idcard&name=$name&actualDay=$actualDay&repaymentNum=$repaymentNum&actualNum=$actualNum&userId=$customerId&userField=$insertId", Log::INFO);
                $result = file_get_contents("http://api.vlink.cn/interface/open/v1/CallAndSave?appId=xxxxxxxx&tel=$tel&timestamp=$time&sign=$sign&repaymentDay=$repaymentDay&arrivalAmount=$arrivalAmount&orderId=$orderId&idcard=$idcard&name=$name&actualDay=$actualDay&repaymentNum=$repaymentNum&actualNum=$actualNum&userId=$customerId&userField=$insertId");
                if($result) {
                    $result_arr = json_decode($result,true);
                    //print_r($result_arr);
                    if($result_arr['description']=='提交成功') {
                        $uniqueId = $result_arr['uniqueId'];
                        D()->execute("UPDATE `consume_history` SET `vlink_id`= '$uniqueId' WHERE  `id` = '$consumeId'");
                    }
                    $ret['data'] = $result_arr;
                    //{"result":"0","uniqueId":"be3ee65f8334a75c186875e92a81cd81","clid":"10109099","description":"提交成功"}
                }*/
                $ret = Constant::getReturn(Constant::SUCCESS);
            } else {
                BusinessException::throwException('已审核');
            }
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    //电话审核通过后放款，生成账单
    public function vlinkNotify() {
        //startTime=1489413780&answerTime=1489413788&endTime=1489413858&tel=13520166164&userField=32332&status=22&uniqueId=3bacf5c1aa3dbf2c57b098ce86cffaf3&fipho=96b28f1e9dda4fb2103e64b685c3d712&userId=1111&orderId=1234

        Log::write("润天回调:".json_encode($_POST), Log::INFO);
        $consumeId = $_POST['orderId'];
        $vlink_id = $_POST['uniqueId'];
        $vlink_status = $_POST['status'];
        $userField = $_POST['userField'];
        $isVerified = $_POST['isVerified'];

        $vlinkloginfo = M('VlinkLog')->where(['vlink_id' => $vlink_id])->find();
        $vlink_log_id = $vlinkloginfo['id'];
        $now = time();
        $data = array(
            'data_id' => $vlink_log_id,
            'data_type' => 2,
            'data_action' =>0,
            'add_time' => $now,
            'status' => 0,
        );
        M('SystemTasks')->add($data);
        //接听
        if($consumeId>0 && $vlink_status=='22') {
            //验证成功
            if($isVerified=='1') {
                D()->execute("UPDATE `user_vlink` SET `status`= '2' WHERE  `id` = '$userField'");
                D()->execute("UPDATE `vlink_log` SET `api_status`= '22',`is_verified`=1,`call_time`='$now'  WHERE  `call_id` = '$userField' and `vlink_id`='$vlink_id'");

                $consumeinfo = M('ConsumeHistory')->where(['id' => $consumeId])->find();
                $customer_id = $consumeinfo['customer_id'];
                $parent_id  = $consumeinfo['id'];
                $money = $consumeinfo['amount']; //到账金额
                $consume_amount = $consumeinfo['consume_amount']; //本金

                $userinfo = D('Customer')->has($customer_id);
                $old_balance_cash_amount = $userinfo['balance_cash_amount'];
                //生成账单
                $result = D()->execute("UPDATE `consume_history` SET `status`=16,`vlink_status`=1  WHERE  `id` = '$consumeId' and `type`=5 and `status` in (12,19)");
                if($result) {
                    $time =time();
                    $repay_id = $consumeinfo['repay_id'];
                    $repayinfo =  M('SysInstallmentPlan')->where(['id' => $repay_id ])->find();
                    $interest_rate = $repayinfo['interest_rate'];
                    $timer = $repayinfo['timer'];
                    //$repayment_time = $time + 30*3600*24; //写死
                    $amount = $consume_amount + $consume_amount*$interest_rate; //利息计算
                    //还款日期=审核通过日期+（借款天数-1）
                    $repayment_time = $time + ($timer-1)*3600*24;
                    D()->execute("UPDATE `consume_history` SET `repayment_time`='$repayment_time'  WHERE  `id` = '$consumeId' and `repayment_time`<>'$repayment_time'");
                    //$repayment_time = $consumeinfo['repayment_time'];//已审核日计算
                    $data = array(
                        'amount' => $amount,
                        'parent_id' => $parent_id,
                        'repayment_time' => $repayment_time,
                        'add_time' => time(),
                    );
                    M('ConsumeInstallmentHistory')->add($data);
                    $money = 1;//测试写死1分钱
                    //增加用户的可提现额度
                    D()->execute("UPDATE `customer` SET `balance_cash_amount` = `balance_cash_amount` + $money  WHERE  `id` = '$customer_id' and `balance_cash_amount`= $old_balance_cash_amount");
                    echo "ok";
                    //自动放款
                    $url = $this->unsResponseHost."/Home/Pay/CustomerWithdraw";
                    $xml_data = array(
                        "customer_id" => $customer_id,
                        "consume_id"=>$consumeId,
                        "money" => $money,
                    );
                    $sign = $this->genSign($xml_data);
                    $xml_data['sign'] = $sign;
                    $this->curlPost($url,$xml_data);
                } else {
                    echo "重复提交";
                }
            } else {
                //身份证验证失败（接听后挂机或身份验证失败）
                D()->execute("UPDATE `vlink_log` SET `api_status`=22, `is_verified`=2 WHERE  `call_id` = '$userField' and `vlink_id`='$vlink_id'");
                $result_type = D()->query("select count(*) as count_v from vlink_log where call_id in (select id from user_vlink  where order_id=$consumeId) and is_verified!=1");
                if($result_type[0]['count_v']>3) {
                    D()->execute("UPDATE `consume_history` SET `status`=19  WHERE  `id` = '$consumeId'");
                }
            }

        } else{
            //呼叫失败(未接电话)
            D()->execute("UPDATE `user_vlink` SET `status`= '3' WHERE  `id` = '$userField'");
            D()->execute("UPDATE `vlink_log` SET `status`= '19',`api_status`=21 WHERE  `call_id` = '$userField' and `vlink_id`='$vlink_id'");
            //D()->execute("UPDATE `consume_history` SET `status`=19  WHERE  `id` = '$consumeId'");

            $result_type = D()->query("select count(*) as count_v from vlink_log where call_id in (select id from user_vlink  where order_id=$consumeId) and is_verified!=1");
            if($result_type[0]['count_v']>3) {
                D()->execute("UPDATE `consume_history` SET `status`=19  WHERE  `id` = '$consumeId'");
            }

        }
    }
    //用户放款（银生宝代付）
    public function CustomerWithdraw() {
        try {
            Log::info_log("*****************CustomerWithdraw用户放款：银生宝代付：*****：");
            Log::rong_write_borrow("*****************CustomerWithdraw用户放款：银生宝代付：*****：");

            $customerId = I('post.customer_id', 0, 'int');
            $consumeId = I('post.consume_id', 0, 'int');
            $money = I('post.money', 0, 'int');

            if (!$customerId || !$money) {
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            D('Customer')->has($customerId);

            $bank_arr =array(
                'ICBC'=>'工商银行',
                'CCB'=>'建设银行',
                'ABC'=>'农业银行',
                'BOC'=>'中国银行',
                'CMBC'=>'民生银行',
                'PSBC'=>'邮储银行',
                'COMM'=>'交通银行',
                'SPDB'=>'浦发银行',
                'CIB'=>'兴业银行',
                'CITIC'=>'中信银行',
                'SPAB'=>'平安银行',
                'CEB'=>'光大银行',
                'BOSC'=>'上海银行',
                'GDB'=>'广发银行',
                'CMB'=>'招商银行',
                'Huaxia Bank'=>'华夏银行',
            );
            //$CustomerBankInfo = M('CustomerBankInfo')->where("customer_id = $customerId and sub_contract_id<>''")->find();
            $CustomerBankInfo = M('CustomerBankInfo')->where("customer_id = $customerId and sub_contract_id<>'' and is_default=1")->find();
            Log::rong_write_borrow("*****************CustomerWithdraw用户放款：银生宝代付|数据库默认银行卡查询：".json_encode($CustomerBankInfo)."*****：");
            Log::borrow_write("*****************CustomerWithdraw用户放款：银生宝代付|数据库默认银行卡查询：".json_encode($CustomerBankInfo)."*****：");

            $recv_user_name = $CustomerBankInfo['card_user_name'];
            $recv_account = $CustomerBankInfo['card_num'];
            $recv_gate_id = $CustomerBankInfo['gate_id'];
            $bank_brhname = $bank_arr[$recv_gate_id];
            Log::borrow_write("*****************CustomerWithdraw用户放款：银生宝代付|数据库默认银行卡所属人查询：".json_encode($recv_user_name)."*****：");
            Log::borrow_write("*****************CustomerWithdraw用户放款：银生宝代付|数据库默认银行卡卡号查询：".json_encode($recv_account)."*****：");
            Log::borrow_write("*****************CustomerWithdraw用户放款：银生宝代付|数据库默认银行卡gate_id查询：".json_encode($recv_gate_id)."*****：");
            Log::borrow_write("*****************CustomerWithdraw用户放款：银生宝代付|数据库默认银行卡中文查询：".json_encode($bank_brhname)."*****：");

            $ConsumeHistoryInfo = M('ConsumeHistory')->where("id = $consumeId")->find();
            $money_consume_amount = $ConsumeHistoryInfo['consume_amount'];
            $money_amount = $ConsumeHistoryInfo['amount'];


            if (!$recv_user_name || !$recv_account || !$recv_gate_id || !$bank_brhname) {
                BusinessException::throwException(Constant::BANK_CARD_NOT_EXIST);
            }
            $customerUser = M('Customer')->where(['id' => $customerId])->find();
            $balance_old = $customerUser['balance_cash_amount'];
            $balance_prepaid = $customerUser['balance_prepaid'];
            $withdraw = $customerUser['withdraw'];

            $new_balance = $balance_old - $money_consume_amount;

            if ($withdraw == 0) {
                Log::borrow_write("*****************CustomerWithdraw用户".$customerId."放款：提现withdraw".json_encode($withdraw));
                //禁止提现
                Log::borrow_write("*****************CustomerWithdraw用户".$customerId."放款：提现失败|withdraw=0*****：");
                Log::rong_write_borrow("*****************CustomerWithdraw用户".$customerId."放款：提现失败|withdraw=0*****：");

                BusinessException::throwException('提现失败');
            }
            if ($new_balance < 0) {
                Log::borrow_write("*****************CustomerWithdraw用户".$customerId."放款：提现失败|new_balance小于0*****：");
                Log::rong_write_borrow("*****************CustomerWithdraw用户".$customerId."放款：提现失败|new_balance小于0*****：");
                BusinessException::throwException(Constant::OUT_OF_RANGE);
            }
            if ($balance_prepaid > 0) {
                Log::borrow_write("*****************CustomerWithdraw用户".$customerId."放款：提现失败|balance_prepaid大于0*****：");
                Log::rong_write_borrow("*****************CustomerWithdraw用户".$customerId."放款：提现失败|balance_prepaid大于0*****：");

                BusinessException::throwException('您有一笔提现，银行正在处理，请稍后重试');
            }

            $CustomerPayLog = M('CustomerPayLog');
            $order_id = $this->trade_no();
            $mer_date = date('Ymd');
            //入库
            $data = array(
                'order_id' => $order_id,
                'customer_id' => $customerId,
                'consume_id'=>$consumeId,
                'money' => $money,
                'balance_old' => $balance_old,
                'status' => 0,
            );

            //修改用户可提现金额 只要发起提现操作，立刻冻结
            M('Customer')->where(['id'=>$customerId,'balance_cash_amount'=>$balance_old])->setField(['balance_cash_amount'=>$new_balance,'balance_prepaid'=>$money]);

            if (false === ($insertId = $CustomerPayLog->add($data))) {
                BusinessException::throwException('提现订单创建失败');
            }
            /*****************************给用户打款操作|本人银行卡校验|************************************/
            //持卡人姓名：$recv_user_name非系统用户本人
            Log::rong_write_borrow("*****************CustomerWithdraw用户".$customerId."真实姓名：".$customerUser['real_name']."|持卡人姓名：".$recv_user_name."|*****：");
            Log::borrow_write("*****************CustomerWithdraw用户".$customerId."真实姓名：".$customerUser['real_name']."|持卡人姓名：".$recv_user_name."|*****：");

            if($customerUser['real_name']!=$recv_user_name){
                Log::rong_write_borrow("*****************CustomerWithdraw用户".$customerId."放款失败：持卡人必须是本人：*****：");
                Log::borrow_write("*****************CustomerWithdraw用户".$customerId."放款失败：持卡人必须是本人：*****：");

                BusinessException::throwException('持卡人必须是本人');
            }
            /*****************************给用户打款操作|本人银行卡校验|************************************/

            $uns_amount = $money*0.01;
            //$uns_amount = 0.01; //测试写死1分钱
            Log::borrow_write("*****************CustomerWithdraw用户".$customerId."放款|实际金额：".$uns_amount."|订单号：".$order_id."|*****：");
            Log::borrow_write("*****************CustomerWithdraw用户".$customerId."放款|取款人：".$recv_user_name."|银行卡：".$recv_account."|*****：");
            Log::rong_write_borrow("*****************CustomerWithdraw用户".$customerId."放款|取款人：".$recv_user_name."|银行卡：".$recv_account."|*****：");

            $result = $this->unsFu($recv_user_name,$recv_account,$order_id,$uns_amount);
            Log::borrow_write("*****************CustomerWithdraw用户".$customerId."放款|返回结果：".json_encode($result)."|*****：");
            Log::rong_write_borrow("*****************CustomerWithdraw用户".$customerId."放款|返回结果：".json_encode($result)."|*****：");
            //$result =[];
            //$result['result_code'] ='0000';
            //$result['result_msg'] ='成功';
            //print_r($result);
            //{"result_code":"0000","result_msg":"交易成功"}
            if($result) {
                Log::write('用户提现-实时付款:'.$html, Log::DEBUG);

                $ret_code = $result['result_code'];
                $ret_msg =   $result['result_msg'];
                $amount =  $money;
                $fee =  0;
                $pay_amount = $amount + $fee;
                $transfer_settle_date =  '';
                $trade_id =  '';
                $trade_state =  '1';
                if($ret_code=='0000') {
                    Log::borrow_write("*****************CustomerWithdraw用户".$customerId."放款|付款成功写库|*****：");

                    $status =2;
                    /*if($ret_code=='00180021') {$status =2;}*/
                    //付款成功写库
                    $sqldata = array('trade_state'=>$trade_state,'ret_code'=>$ret_code,'status'=>$status,'amount'=>$amount,'fee'=>$fee,'pay_amount'=>$pay_amount,'trade_id'=>$trade_id);
                    $CustomerPayLog->where(['id'=>$insertId,'status'=>0])->setField($sqldata);
                    //修改商户可提现金额 只要发起提现操作，立刻冻结
                    //M('Customer')->where(['id'=>$customerId,'balance_cash_amount'=>$balance_old])->setField(['balance_cash_amount'=>$new_balance]);

                    //$order_id = $data->H_table['order_id'];
                    $ret = Constant::getReturn(Constant::SUCCESS);
                    $ret['data'] = array('order_id'=>$order_id,'trade_no'=>$trade_id,'balance'=>$new_balance);

                } else {
                    Log::borrow_write("*****************CustomerWithdraw用户".$customerId."放款|付款失败|*****：");

                    //付款失败
                    $status = 3;
                    $sqldata = array('ret_msg'=>$ret_msg,'ret_code'=>$ret_code,'trade_state'=>$trade_state,'status'=>$status,'amount'=>$amount,'fee'=>$fee,'pay_amount'=>$pay_amount,'transfer_settle_date'=>$transfer_settle_date,'trade_id'=>$trade_id);
                    $CustomerPayLog->where(['id'=>$insertId,'status'=>0])->setField($sqldata);
                    BusinessException::throwException($ret_code.$ret_msg);
                    //BusinessException::throwException(Constant::FAILED);
                }
            }

        } catch (BusinessException $e) {
            $this->ajaxReturn(['code' => $e->getCode(), 'msg' => $e->getMessage()]);
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }
    /**
    /**
     * 获取银行卡列表
     */
    public function getBankList() {
        try {
            $customerId = I('post.customer_id', 0, 'int');
            D('Customer')->has($customerId);
            //BusinessException::throwException(201,'运营的');
            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data'] = D('CustomerBankInfo')->getList($customerId);
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }
    //订单号生成
    public function trade_no() {
        list($usec, $sec) = explode(" ", microtime());
        $usec = substr(str_replace('0.', '', $usec), 0 ,4);
        $str  = rand(10,99);
        return date("ymdHis").$usec.$str;
    }
    //获取下个月或者上个月
    private function GetMonth($sign="1")
    {
        //$ts = mktime(0, 0, 0, date('n') + 1, 10);
        //echo  date('Y-m-d', $ts);

        //得到系统的年月
        $tmp_date=date("Ym");
        //切割出年份
        $tmp_year=substr($tmp_date,0,4);
        //切割出月份
        $tmp_mon =substr($tmp_date,4,2);
        $tmp_nextmonth=mktime(0,0,0,$tmp_mon+1,1,$tmp_year);
        $tmp_forwardmonth=mktime(0,0,0,$tmp_mon-1,1,$tmp_year);
        if($sign==0){
            //得到当前月的下一个月
            return $fm_next_month=date("Y-m",$tmp_nextmonth);
        }else{
            //得到当前月的上一个月
            return $fm_forward_month=date("Y-m",$tmp_forwardmonth);
        }
    }


    protected function gen_nonce(){
        return md5(uniqid('', true));
    }

    protected function gen_mch_billno(){
        $MCH_ID = Environment::$conf['mpConfig']['mchID'];
        return $MCH_ID.date('Ymd').time();
    }

    function genSign(array $param) {
        //0. 删除原数据中自带的sign值,防止干扰计算结果
        unset($param['sign']);
        //1. 按key由a到z排序
        ksort($param);
        foreach ($param as $key => $value) {
            if (is_array($value)) {
                $param[$key] = $this->genSign($value);
            }
        }
        //2. 生成以&符链接的key=value形式的字符串
        $paramString = urldecode(http_build_query($param));

        //3. 拼接我们的服务秘钥，并md5加密
        $sign = md5($paramString . 'secret@9maibei.com');
        return $sign;
    }

    function curlPost($url,$xml_data) {
        $ch=curl_init($url);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        //curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        //curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));

        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($xml_data));
        $response = curl_exec($ch);
        if(curl_errno($ch))
        {
            print curl_error($ch);
        }
        curl_close($ch);
        //return $response;
    }

    public function unsNotify() {
        Log::write("银生宝代扣异步通知:".json_encode($_POST), Log::INFO);
        Log::pay_write('**********银生宝代扣异步通知：'.json_encode($_POST));
        //{"result_code":"0000","amount":"0.01","result_msg":"","mac":"9E12D2CBC5BF5A57C41438E0F339B963","orderId":"14881805185186"}
        //accountId=&orderId=201504081621&amount=0.26&result_code=0000&result_msg=余额不足&key=123456
        //print_r($_POST);
        $check_mac = strtoupper(md5("accountId=".$this->unsAccountId."&orderId=".$_POST['orderId']."&amount=".$_POST['amount']."&result_code=".$_POST['result_code']."&result_msg=".$_POST['result_msg']."&key=".$this->unsKeys.""));
        $mac = $_POST['mac'];
        if($mac==$check_mac) {
            Log::write("银生宝代扣异步通知结果:success", Log::INFO);
            $ret_msg = $_POST['result_msg'];
            $ret_code = $_POST['result_code'];
            $CustomerBillPayLog = M('CustomerBillPayLog');
            $order_id = $_POST['orderId'];
            /************************/
            $redis = new Redis();
            /************************/
            if($ret_code=='0000') {

                $sqldata = array('ret_msg'=>'success','pay_time'=>time(),'status'=>1);
                $CustomerBillPayLog->where(['order_id'=>$order_id,'pay_time'=>0])->setField($sqldata);

                $CustomerBillPayLogInfo = $CustomerBillPayLog->where(['order_id' => $order_id])->find();
                $consume_id = $CustomerBillPayLogInfo['consume_id'];
                $customer_id = $CustomerBillPayLogInfo['customer_id'];

                if($consume_id>0) {
                    /****这里扣款成功修改status给贷后分单用，防止撤单分单出现已还款仍能撤分单***/
                    $ConsumeUserInfo = M('consume_user')->where("consume_id = $consume_id and status = 1")->find();
                    if (isset($ConsumeUserInfo) && !empty($ConsumeUserInfo)) {
                        $ConsumeUserStatusInfo = M('consume_user')->where("consume_id = $consume_id and status = 1")->setField(array('status'=>2));
                    }
                    // 目前bochen要撤单不分回款未回款，目前无条件撤回,所以这里不做状态改变，打开则为做了状态改变
                    /****这里扣款成功修改status给贷后分单用，防止撤单分单出现已还款仍能撤分单***/
                    Log::pay_write('**********银生宝代扣异步通知|订单|'.$order_id.'|成功');
                    /********************异步通知结果***************/
                    //M('ConsumeHistory')->where(['id'=>$consume_id,'update_time'=>0])->setField(['status'=>3,'update_time'=>time()]);
                    $test_consume=M('ConsumeHistory')->where(['id'=>$consume_id,'type'=>5,'status'=>1])->setField(['status'=>3,'update_time'=>time()]);
                    $test_install=M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->setField(['status'=>1,'update_time'=>time()]);
                    $trd=M('Customer')->where(['id'=>$customer_id])->setField(['balance_cash_amount'=>200000,'cash_amount'=>0]);
                    Log::pay_write('**********银生宝代扣异步通知|操作ConsumeHistory|结果：'.json_encode($test_consume).'|');
                    Log::pay_write('**********银生宝代扣异步通知|ConsumeInstallmentHistory|结果：'.json_encode($test_install).'|');
                    Log::pay_write('**********银生宝代扣异步通知|Customer|结果：'.json_encode($trd).'|');
                    Log::pay_write('**********银生宝代扣异步通知|订单|'.$order_id.'|成功');
                    /**********************处理中*************************/
                    //查询用户订单信息
                    $consume = M('ConsumeHistory')->where(['id'=>$consume_id])->find();
                    if ($consume['status'] == 3){
                        $paylog = $CustomerBillPayLog->where(['order_id'=>$order_id])->find();
                        $consumehistory = M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->find();
                        if ($paylog['amount'] != $consumehistory['amount']){
                            $scredit = D('CustomerAuth')->saveCustomerAuth($consume['customer_id']);
                            if (!$scredit){
                                BusinessException::throwException(Constant::INVALID_PARAMETER);
                            }
                            $czhima = D('Customer')->saveCustomerzhima($consume['customer_id']);
                            if (!$czhima){
                                BusinessException::throwException(Constant::INVALID_PARAMETER);
                            }
                        }
                    }
                    $CustomerBillPayLogInfo = $CustomerBillPayLog->where(['order_id' => $order_id])->find();
                    $key='repay-request'.$CustomerBillPayLogInfo['consume_id'];
                    if($redis->get($key)){
                        $redis_res=$redis->rm($key);
                        Log::pay_write("银生宝代扣异步通知结果|订单".$order_id."|删除redis处理中|key:".$key.'|');
                        Log::pay_write("银生宝代扣异步通知结果订单".$order_id."|删除redis处理中的结果|".$redis_res.'|');
                    }
                    Log::pay_write("银生宝代扣异步通知结果||order_id:".$order_id.'|成功');
                    /**********************处理中*************************/
                }
            } else {
                $CustomerBillPayLogInfo = $CustomerBillPayLog->where(['order_id' => $order_id])->find();
                $consume_id = $CustomerBillPayLogInfo['consume_id'];
                $repayStatus = M('ConsumeHistory')->where(['id'=>$consume_id])->setField(['repay'=>0, 'repay_add_time'=>0]);
                Log::pay_write("订单".$consume_id."银生宝代扣异步ConsumeHistory设置repay通知结果||repay:". ($repayStatus ? 0 : 1) .'|');
                //$ret_msg = 'fail';
                $sqldata = array('ret_msg'=>$ret_msg,'ret_code'=>$ret_code);
                $CustomerBillPayLog->where(['order_id'=>$order_id,'pay_time'=>0])->setField($sqldata);
                /**********************处理中*************************/

                $CustomerBillPayLogInfo = $CustomerBillPayLog->where(['order_id' => $order_id])->find();
                $key='repay-request'.$CustomerBillPayLogInfo['consume_id'];
                if($redis->get($key)){
                    $redis_res=$redis->rm($key);
                    Log::pay_write("银生宝代扣异步通知结果|订单".$order_id."|删除redis处理中|key:".$key.'|');
                    Log::pay_write("银生宝代扣异步通知结果|订单".$order_id."|删除redis处理中的结果|".$redis_res.'|');
                }
                Log::pay_write("银生宝代扣异步通知结果||order_id:".$order_id.'|失败');
                /**********************处理中*************************/
            }

            echo 'success';
        }
    }
    /*根据订单号查询是否扣款成功*/
    public  function  searchX(){
//echo 9999999999999;die;

        $order_id=I('get.orderId');
        $CustomerBillPayLog = M('CustomerBillPayLog');
        $aa=$CustomerBillPayLog->field("id,order_id,consume_id,customer_id")->where(['order_id'=>$order_id])->find();
        $consume_id=$aa['consume_id'];
        $insertId=$aa['id'];
        $customerId=$aa['customer_id'];
        $resultstatu = $this->unsPaystatu($order_id);
        Log::pay_write('**********查询用户是否实际还款返回结果status：'.$resultstatu['status']);
        Log::pay_write('**********查询用户是否实际还款返回结果：desc:'.$resultstatu['desc']);
        Log::pay_write('**********查询用户是否实际还款返回结果：result_msg:'.$resultstatu['result_msg']);
        Log::pay_write('**********查询用户是否实际还款返回结果status：'.$resultstatu['status']);
        Log::pay_write('**********查询用户是否实际还款返回结果：desc:'.$resultstatu['desc']);
        Log::pay_write('**********查询用户是否实际还款返回结果：result_msg:'.$resultstatu['result_msg']);

        if($resultstatu['status'] == '00'){
            Log::pay_write('**********查询用户'.$order_id.'是否实际还款返回结果status：00|成功');


            /**********************处理中订单|**********************************/
            //$key='处理中订单-'.$consume_id;
            //$redis_res=$redis->set($key,'00');
            //Log::pay_write('**********|订单号码：'.$order_id.'|查询用户是否实际还款返回结果|存入redis|'.json_encode($redis_res));
            //Log::pay_write('**********|订单号码：'.$order_id.'|存入redis|key:'.$key.'|value:'. $redis_res=$redis->get($key));
            /**********************处理中订单|**********************************/
            //还款成功写库
            //$sqldata = array('trade_state'=>$trade_state,'ret_code'=>$ret_code,'status'=>2);
            $sqldata = array('trade_state'=>$resultstatu['result_msg'],'ret_msg'=>'success','pay_time'=>time(),'ret_code'=>$resultstatu['result_code'],'status'=>2);
            $CustomerBillPayLog->where(['id'=>$insertId,'status'=>0])->setField($sqldata);
            $ret = Constant::getReturn(Constant::SUCCESS);
//            $ret['data'] = array('order_id'=>$order_id,'trade_no'=>$order_id,'amount' => $amount,'pay_action' => $pay_action,'customer_id' => $customerId,'pay_time' => date('Y-m-d H:i:s',time()));

            //更新订单状态到已还款完成
            M('ConsumeHistory')->where(['id'=>$consume_id])->setField(['status'=>3,'update_time'=>time()]);
            M('Customer')->where(['id'=>$customerId])->setField(['cash_amount'=>0]);
            M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id,'update_time'=>0])->setField(['status'=>1,'update_time'=>time(),"final_amount"=>0]);
            //M('Customer')->where(['id'=>$customerId])->setField(['cash_amount'=>0]);

            /****这里扣款成功修改status给贷后分单用，防止撤单分单出现已还款仍能撤分单***/
            $ConsumeUserInfo = M('consume_user')->where("consume_id = $consume_id and status = 1")->find();
            if (isset($ConsumeUserInfo) && !empty($ConsumeUserInfo)) {
                $ConsumeUserStatusInfo = M('consume_user')->where("consume_id = $consume_id and status = 1")->setField(array('status'=>2));
            }
            // 目前bochen要撤单不分回款未回款，目前无条件撤回,所以这里不做状态改变，打开则为做了状态改变
            /****这里扣款成功修改status给贷后分单用，防止撤单分单出现已还款仍能撤分单***/

        }else if($resultstatu['status'] == '20'){
            Log::pay_write('**********查询用户'.$order_id.'是否实际还款返回结果status：20|余额不足');

            /**********************处理中订单|**********************************/
            //$key='处理中订单-'.$consume_id;
            //$redis_res=$redis->set($key,'20');
            //Log::pay_write('**********|订单号码：'.$order_id.'|查询用户是否实际还款返回结果|存入redis|'.json_encode($redis_res));
            //Log::pay_write('**********|订单号码：'.$order_id.'|存入redis|key:'.$key.'|value:'. $redis_res=$redis->get($key));
            /**********************处理中订单|**********************************/
            $status = 3;
            $sqldata = array('ret_msg'=>'银行卡余额不足','ret_code'=>1111,'status'=>$status);
            $CustomerBillPayLog->where(['id'=>$insertId,'status'=>0])->setField($sqldata);
            //手动输入的预扣金额为零
            M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id,'update_time'=>0])->setField(["final_amount"=>0]);
            $this->ajaxReturn(['code' => 1111, 'msg' => '银行卡上余额不足']);
            /********************************还款处理中**************************************/

        }elseif($resultstatu['status'] == '10'){
            Log::pay_write('**********|订单号码：'.$order_id.'|查询用户是否实际还款返回结果|：还款处理中');

            $this->ajaxReturn(['code' => 10, 'msg' => '正在还款，请稍后']);
        }
    }


    public function NewunsNotify() {
        Log::pay_write('**********银生宝续借|代扣异步通知：'.json_encode($_POST));
        Log::write("银生宝续借|代扣异步通知:".json_encode($_POST), Log::INFO);
        //{"result_code":"0000","amount":"0.01","result_msg":"","mac":"9E12D2CBC5BF5A57C41438E0F339B963","orderId":"14881805185186"}
        //accountId=&orderId=201504081621&amount=0.26&result_code=0000&result_msg=余额不足&key=123456
//           print_r($_POST);
        $check_mac = strtoupper(md5("accountId=".$this->unsAccountId."&orderId=".$_POST['orderId']."&amount=".$_POST['amount']."&result_code=".$_POST['result_code']."&result_msg=".$_POST['result_msg']."&key=".$this->unsKeys.""));
        $mac = $_POST['mac'];
        if($mac==$check_mac) {
            Log::write("银生宝代扣异步通知结果:success", Log::INFO);
            $ret_msg = $_POST['result_msg'];
            $ret_code = $_POST['result_code'];
            $CustomerBillPayLog = M('CustomerBillPayLog');
            $order_id = $_POST['orderId'];
            /************************/
            $redis = new Redis();
            /************************/
            if($ret_code=='0000') {
                Log::pay_write('**********银生宝续借代扣开始更新CustomerBillPayLog表|'.json_encode($CustomerBillPayLog));
                $sqldata = array('ret_msg'=>'success','pay_time'=>time(),'status'=>1);
                $CustomerBillPayLog->where(['order_id'=>$order_id,'pay_time'=>0])->setField($sqldata);

                $CustomerBillPayLogInfo = $CustomerBillPayLog->where(['order_id' => $order_id])->find();
                Log::pay_write('**********银生宝续借代扣结束更新CustomerBillPayLog表|'.json_encode($CustomerBillPayLogInfo));
                $consume_id = $CustomerBillPayLogInfo['consume_id'];
                $customer_id = $CustomerBillPayLogInfo['customer_id'];

                if($consume_id>0) {
                    Log::pay_write('**********银生宝续借代扣异步通知|订单|'.$order_id.'|成功');

                    /**********************************开启回掉函数更改续借日期******************************************/
                    $repay_time=  M('ConsumeHistory')->where(['id'=>$consume_id])->field('repayment_time,repay_id')->find();
                    $repay_time_=  M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->field('repayment_time')->find();
                    //之前还款时间
                    $repay_time_old=$repay_time_['repayment_time'];
                    if(!$repay_time_old){//如果不存在|默认取当前当前
                        $repay_time_old=time();
                    }
                    //根据用户选择的产品|延迟天数
                    $repay_long=($repay_time['repay_id']=='1')?30:($repay_time['repay_id']=='2'?14:30);
                    /****这里扣款成功修改status给贷后分单用，防止撤单分单出现已还款仍能撤分单***/
                    //逾期后续借情况，要删除consume_user表里的相应记录
                    $ConsumeUserInfo = M('consume_user')->where("consume_id = $consume_id and status = 1")->find();
                    if (isset($ConsumeUserInfo) && !empty($ConsumeUserInfo)) {
                        $ConsumeUserStatusInfo = M('consume_user')->where("consume_id = $consume_id and status = 1")->setField(array('status'=>3));//逾期续借状态变为3记录在表里
                    }
                    /****这里扣款成功修改status给贷后分单用，防止撤单分单出现已还款仍能撤分单***/
                    // M('ConsumeHistory')->where(['id'=>$consume_id])->setField(['repayment_time'=>$repay_time_old+$repay_long*24*3600]);
                    // M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->setField(['update_time'=>time(),'repayment_time'=>$repay_time_old+$repay_long*24*3600]);
                    /**********************************开启回掉函数更改续借日期******************************************/
                    M('Customer')->where(['id'=>$customer_id])->setField(['balance_cash_amount'=>100000]);
                    /***|展期成功后|展期控制清零|***/
                    M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->setField(['allow_renew'=>0]);
                    /***********************同时更新续借时间***********************/
                    $repay_time=  M('ConsumeHistory')->where(['id'=>$consume_id])->field('repayment_time,repay_id')->find();
                    $repay_time_=  M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->field('repayment_time')->find();
                    $ConsumeHistory = M('consume_history')->where(['id' => $consume_id])->find();
                    //之前还款时间
                    $repay_time_old=$repay_time_['repayment_time'];
                    if(!$repay_time_old){//如果不存在|默认取当前当前
                        $repay_time_old=time();
                    }
                    //根据用户选择的产品|延迟天数--查库
                    //$repay_long=($repay_time['repay_id']=='1')?30:($repay_time['repay_id']=='2'?14:30);
                    $repay_time['repay_id']=($repay_time['repay_id']==1)?3:$repay_time['repay_id'];
                    $repay_long = M('SysInstallmentPlan')->where(['id' =>  $repay_time['repay_id'], 'publish' => 1, 'target' => 3])->find();
                    M('ConsumeHistory')->where(['id'=>$consume_id])->setField(['repayment_time'=>$repay_time_old+$repay_long['timer']*24*3600,'renew_id'=>$ConsumeHistory['renew_id']+1]);
                    //M('ConsumeHistory')->where(['id'=>$consume_id])->setField(['repayment_time'=>strtotime(date('Y-m-d H:i:s',strtotime('+1month'))),'renew_id'=>$ConsumeHistory['     renew_id']+1]);
                    M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->setField(['update_time'=>time(),'repayment_time'=>$repay_time_old+$repay_long['timer']*24*3600]);
                    //M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->setField(['update_time'=>time(),'repayment_time'=>strtotime(date('Y-m-d H:i:s',strtotime('+     1month')))]);
                    // M('Customer')->where(['id'=>$customer_id])->setField(['balance_cash_amount'=>$uns_amount]);
                    Log::pay_write("银生宝续借代扣异步通知结果订单号".$consume_id."|用户为|".$customer_id.'|');
                    /***********************同时更新续借时间***********************/
                    /**********************处理中*************************/

                    $CustomerBillPayLogInfo = $CustomerBillPayLog->where(['order_id' => $order_id])->find();
                    $key='处理中续借订单-'.$CustomerBillPayLogInfo['consume_id'];
                    if($redis->get($key)){
                        $redis_res=$redis->rm($key);
                        /***********************同时更新续借时间***********************/
                        // $repay_time=  M('ConsumeHistory')->where(['id'=>$consume_id])->field('repayment_time,repay_id')->find();
                        //     $repay_time_=  M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->field('repayment_time')->find();
                        //   $ConsumeHistory = M('consume_history')->where(['id' => $consume_id])->find();
                        //之前还款时间
                        //  $repay_time_old=$repay_time_['repayment_time'];
                        // if(!$repay_time_old){//如果不存在|默认取当前当前
                        //    $repay_time_old=time();
                        // }
                        //根据用户选择的产品|延迟天数--查库
                        //$repay_long=($repay_time['repay_id']=='1')?30:($repay_time['repay_id']=='2'?14:30);
                        // $repay_time['repay_id']=($repay_time['repay_id']==1)?3:$repay_time['repay_id'];
                        // $repay_long = M('SysInstallmentPlan')->where(['id' =>  $repay_time['repay_id'], 'publish' => 1, 'target' => 3])->find();
                        // M('ConsumeHistory')->where(['id'=>$consume_id])->setField(['repayment_time'=>$repay_time_old+$repay_long['timer']*24*3600,'renew_id'=>$ConsumeHistory['renew_id']+1]);
                        //M('ConsumeHistory')->where(['id'=>$consume_id])->setField(['repayment_time'=>strtotime(date('Y-m-d H:i:s',strtotime('+1month'))),'renew_id'=>$ConsumeHistory['renew_id']+1]);
                        // M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->setField(['update_time'=>time(),'repayment_time'=>$repay_time_old+$repay_long['timer']*24*3600]);
                        //M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->setField(['update_time'=>time(),'repayment_time'=>strtotime(date('Y-m-d H:i:s',strtotime('+1month')))]);
                        // M('Customer')->where(['id'=>$customer_id])->setField(['balance_cash_amount'=>$uns_amount]);

                        /***********************同时更新续借时间***********************/
                        Log::pay_write("银生宝续借代扣异步通知结果|订单".$order_id."|删除redis处理中|key:".$key.'|');
                        Log::pay_write("银生宝续借代扣异步通知结果订单".$order_id."|删除redis处理中的结果|".$redis_res.'|');
                    }
                    Log::pay_write("银生宝续借代扣异步通知结果||order_id:".$order_id.'|成功');
                    /**********************处理中*************************/
                }
            } else {
                //$ret_msg = 'fail';
                $sqldata = array('ret_msg'=>$ret_msg,'ret_code'=>$ret_code);
                $CustomerBillPayLog->where(['order_id'=>$order_id,'pay_time'=>0])->setField($sqldata);
                $CustomerBill = $CustomerBillPayLog->field("customer_id,amount,consume_id")->where(['order_id'=>$order_id])->find();
                $customer_id = $CustomerBill['customer_id'];
                $amount = $CustomerBill['amount'];
                $consumeId = $CustomerBill['consume_id'];

                //预扣金额回滚
                M('Customer')->execute("UPDATE `customer` SET `balance_cash_amount` = `balance_cash_amount` + `balance_prepaid`,`balance_prepaid`=0 where `id` = $customer_id and `balance_prepaid` =$amount");

                //$ret_msg = 'fail';
                $sqldata = array('ret_msg'=>$ret_msg,'ret_code'=>$ret_code);
                $CustomerPayLog->where(['order_id'=>$order_id,'pay_time'=>0])->setField($sqldata);
                // D()->execute("UPDATE `consume_history` SET `status`=17  WHERE  `id` = '$consumeId'");
                /**********************处理中*************************/

                $CustomerBillPayLogInfo = $CustomerBillPayLog->where(['order_id' => $order_id])->find();
                $key='处理中续借订单-'.$CustomerBillPayLogInfo['consume_id'];
                if($redis->get($key)){
                    $redis_res=$redis->rm($key);
                    Log::pay_write("银生宝续借代扣异步通知结果|订单".$order_id."|删除redis处理中|key:".$key.'|');
                    Log::pay_write("银生宝续借代扣异步通知结果|订单".$order_id."|删除redis处理中的结果|".$redis_res.'|');
                }
                Log::pay_write("银生宝续借代扣异步通知结果||order_id:".$order_id.'|失败');
                /**********************处理中*************************/
            }

            echo 'success';
        }
    }

    public function unsNotifyFu() {
        Log::pay_write('**********银生宝代付异步通知：'.json_encode($_GET));
        Log::write("银生宝代付异步通知:".json_encode($_GET), Log::INFO);
        //Home/Pay/unsNotifyFu?result_code=0000&amount=0.01&result_msg=&mac=9E13C923665BD111F0DECF66AD8E3409&orderId=14881805185188
        //print_r($_GET);
        $check_mac = strtoupper(md5("accountId=".$this->unsAccountId."&orderId=".$_GET['orderId']."&amount=".$_GET['amount']."&result_code=".$_GET['result_code']."&result_msg=".$_GET['result_msg']."&key=".$this->unsKeys.""));
        $mac = $_GET['mac'];
        if($mac==$check_mac) {
            Log::write("银生宝代付异步通知结果:success", Log::INFO);
            //回调成功写库
            $CustomerPayLog = M('CustomerPayLog');
            $order_id =  $_GET['orderId'];
            $transfer_date =  '';
            $transfer_settle_date =  '';
            $ret_code = $_GET['result_code'];
            $amount = $_GET['amount']*100;
            $ret_msg = $_GET['result_msg'];

            $CustomerPayLogInfo = $CustomerPayLog->where(['order_id' => $order_id])->find();
            $customer_id = $CustomerPayLogInfo['customer_id'];
            $money = $CustomerPayLogInfo['money'];
            $consumeId = $CustomerPayLogInfo['consume_id'];

            if($ret_code=='0000') {
                Log::borrow_write("+++银生宝代付异步通知|代付成功|用户：".$customer_id.'|订单号：'.$order_id.'|'.$ret_code.$ret_msg.'+++');
                //预扣金额清零
                M('Customer')->where(['id'=>$customer_id,'balance_prepaid'=>$amount])->setField(['balance_prepaid'=>0]);
                $ret_msg = 'success';
                $sqldata = array('ret_msg'=>$ret_msg,'pay_time'=>time(),'status'=>1);
                $CustomerPayLog->where(['order_id'=>$order_id,'pay_time'=>0])->setField($sqldata);
                D()->execute("UPDATE `consume_history` SET `status`=1  WHERE  `id` = '$consumeId'");
            } else {
                Log::borrow_write("+++银生宝代付异步通知|代付失败|用户：".$customer_id.'|订单号：'.$order_id.'|'.$ret_code.$ret_msg.'+++');
                //预扣金额回滚
                M('Customer')->execute("UPDATE `customer` SET `balance_cash_amount` = `balance_cash_amount` + `balance_prepaid`,`balance_prepaid`=0 where `id` = $customer_id and `balance_prepaid` =$amount");
                //$ret_msg = 'fail';
                $sqldata = array('ret_msg'=>$ret_msg,'ret_code'=>$ret_code);
                $CustomerPayLog->where(['order_id'=>$order_id,'pay_time'=>0])->setField($sqldata);
                D()->execute("UPDATE `consume_history` SET `status`=17  WHERE  `id` = '$consumeId'");
//                $customer_ids=M("consume_history",null)->where("id='$consumeId'")->field("customer_id")->find();
//                D()->execute("UPDATE consume_history SET `status`=6 WHERE `customer_id`='$customer_ids[customer_id]' AND `type`='4'");
                die;
            }
            echo 'success';
        }
    }
    /***
     * 蜡笔重新推单方法
     ***/
    public function Labi(){
        $idNum=I("get.idNum");
        // $add_time=I("get.add_time");
        $add_times=I("get.add_time");
        // $add_time=date("Y-m-d",strtotime($add_times));
        $add_time=substr($add_times,0,10);

        //资金
        $financing = D("Customer")->where("id_num = ".$idNum)->find();
        // $sql="SELECT customer_id,id,amount,add_time FROM consume_history WHERE customer_id='$financing[id]' AND type=5 AND (from_unixtime(add_time,'%Y-%m-%d'))='$add_time' limit 1";
        $sql="SELECT customer_id,id,consume_amount,add_time FROM consume_history WHERE customer_id=".$financing['id']." AND type=5 AND (from_unixtime(add_time,'%Y-%m-%d'))='$add_time' limit 1";

        $result=M()->query($sql);
        //身份证号在配置白名单，略过资金端引擎
        //if(!in_array($financing['id_num'],$params[WHITE_LIST])) {
        $financing['need_money'] = $result[0]['consume_amount']; //单位分
        $financing['consume_id'] = $result[0]['id'];
        Log::borrow_write("*****************重新推单|资金引擎|：*****：");
        $ret = BaseHook::executePayWayHook("PAYWAY_ENGINE_HOOK", $financing);
        Log::borrow_write("*****************推单成功|资金引擎|执行结果：".json_encode($ret)."*****：");
    }

    //绑卡
    public function unsBind($cardNo,$phoneNo,$name,$idCardNo) {
        $url = $this->unsRequestHost.'/unspay-external/subcontract/signSimpleSubContract';
        //$cardNo = '62220202000473XXX';
        //$phoneNo = '15010258909';
        //$name = '杨XX';
        //$idCardNo = '36242519840213XXXX';
        $xml_data = array(
            'accountId'=>$this->unsAccountId,
            'contractId'=>$this->unsContractId,
            'name'=>$name,
            'phoneNo'=>$phoneNo,
            'cardNo'=>$cardNo,
            'idCardNo'=>$idCardNo,
            'startDate'=>date('Ymd'),
            'endDate'=>'20180301',
            /*'cycle'=>'',//扣款频率
            'triesLimit'=>'',//扣款次数限制*/
        );

        $sign = $this->unsGenSign($xml_data);
        $xml_data['mac'] = $sign;
        $xml_data = http_build_query($xml_data);
        $result = $this->unsCurlPost($url,$xml_data);

        $result_arr = json_decode($result,true);
        Log::rong_write_borrow("***--绑定卡操作|".$result."***");

        //{"result_code":"0000","result_msg":"交易成功","subContractId":"1279789"}
        return $result_arr;
        //exit;
    }

    //代扣 1279789
    public function unsPay($subContractId,$orderId,$amount) {
        $url = $this->unsRequestHost.'/unspay-external/delegateCollect/collect';
        $xml_data = array(
            'accountId'=>$this->unsAccountId,
            'subContractId'=>$subContractId, //1279789
            'orderId'=>$orderId, //14881805185186
            'purpose'=>'消费分期还款',
            'amount'=>$amount, //0.01
            /*'phoneNo'=>'18634364997', //银行预留手机号*/
            'responseUrl'=>$this->unsResponseHost.'/Home/Pay/unsNotify',
        );

        $sign = $this->unsGenSign($xml_data);
        $xml_data['mac'] = $sign;
        $xml_data = http_build_query($xml_data);
        Log::pay_write('**********用户实际还款参数：'.$xml_data);
        Log::pay_write('**********用户实际还款url：'.$url);
        $result = $this->unsCurlPost($url,$xml_data);
        Log::pay_write('**********用户实际还款执行结果：'.$result);
        $result_arr = json_decode($result,true);
        //{"result_code":"0000","result_msg":"交易成功"}
        return $result_arr;
        //exit;
    }


    //实际交易成功是否成功
    public function unsPaystatu($orderId) {
        $url = $this->unsRequestHost.'/unspay-external/delegateCollect/queryOrderStatus';
        $xml_data = array(
            'accountId'=>$this->unsAccountId,
            'orderId'=>$orderId, //14881805185186
        );

        $sign = $this->unsGenSign($xml_data);
        $xml_data['mac'] = $sign;
        $xml_data = http_build_query($xml_data);
        Log::write("*****订单号".$orderId."*******用户续借|查询交易是否成功|请求数据****************".json_encode($xml_data));
        Log::pay_write('*****订单号：'.$orderId.'*****用户续借|查询交易是否成功|请求数据：'.json_encode($xml_data));
        Log::write("************用户续借|查询交易是否成功|请求数据url：****************".$url);
        Log::pay_write('***订单号：'.$orderId.'*******用户续借|查询交易是否成功|请求数据url:'.$url);
        Log::pay_write('**********查询用户实际还款参数：'.$xml_data);
        Log::pay_write('**********查询用户实际还款url：'.$url);
        $result = $this->unsCurlPost($url,$xml_data);
        Log::pay_write('******订单号'.$orderId.'****查询用户实际还款返回结果：'.$result);
        Log::write("************用户续借|查询交易是否成功|请求数据返回结果：****************".$result);
        Log::pay_write('**********用户续借|查询交易是否成功|请求数据返回结果：'.$result);

        $result_arr = json_decode($result,true);

        //{"result_code":"0000","result_msg":"交易成功"}
        return $result_arr;
        //exit;
    }


    //续贷代扣 1279789
    public function NewunsPay($subContractId,$orderId,$amount) {
        $url = $this->unsRequestHost.'/unspay-external/delegateCollect/collect';
        $xml_data = array(
            'accountId'=>$this->unsAccountId,
            'subContractId'=>$subContractId, //1279789
            'orderId'=>$orderId, //14881805185186
            'purpose'=>'消费分期还款',
            'amount'=>$amount, //0.01
            /*'phoneNo'=>'18634364997', //银行预留手机号*/
            'responseUrl'=>$this->unsResponseHost.'/Home/Pay/NewunsNotify',
        );

        $sign = $this->unsGenSign($xml_data);
        $xml_data['mac'] = $sign;
        $xml_data = http_build_query($xml_data);
        Log::pay_write('**********用户续借执行数据：'.$xml_data);
        Log::pay_write('**********用户续借执行url：'.$url);
        Log::write('********************用户续借|续借扣款请求数据：'.json_encode($xml_data).'*******************', Log::DEBUG);
        $result = $this->unsCurlPost($url,$xml_data);
        Log::pay_write('**********用户续借执行url返回结果：'.$result);
        Log::write('********************用户续借|续借扣款返回数据：'.$result.'*******************', Log::DEBUG);

        $result_arr = json_decode($result,true);
        //{"result_code":"0000","result_msg":"交易成功"}
        return $result_arr;
        //exit;
    }

    //代付(提现)
    public function unsFu($name,$cardNo,$orderId,$amount) {
        $url = $this->unsRequestHost.'/unspay-external/delegatePay/pay';
        //unspay-external/delegatePay/pay
        $xml_data = array(
            'accountId'=>$this->unsAccountId,
            'name'=>$name,//杨XX
            'cardNo'=>$cardNo,//622202020004736XXXX
            'orderId'=>$orderId,//14881805185189
            'purpose'=>'用户提现',
            'amount'=>$amount,//0.01
            'responseUrl'=>$this->unsResponseHost.'/Home/Pay/unsNotifyFu',
        );

        $sign = $this->unsGenSign($xml_data);
        $xml_data['mac'] = $sign;
        $xml_data = http_build_query($xml_data);
        $result = $this->unsCurlPost($url,$xml_data);
        $result_arr = json_decode($result,true);
        //{"result_code":"0000","result_msg":"交易成功"}

//         echo $url;
//         echo "<pre>";
//         var_dump($xml_data);
//         echo "<pre />";

//         echo "---------------------------";
//         var_dump($result_arr);
        return $result_arr;
        //exit;
    }

    function unsCurlPost($url,$xml_data) {

        //$header[] = "Content-Type: application/json;charset=utf-8";
        $ch=curl_init($url);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 300);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
        //curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        //curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data);
        $response = curl_exec($ch);
        if(curl_errno($ch))
        {
            print curl_error($ch);
        }
        curl_close($ch);
        return $response;
    }

    function unsGenSign(array $param) {
        //0. 删除原数据中自带的sign值,防止干扰计算结果
        unset($param['sign']);

        foreach ($param as $key => $value) {
            if (is_array($value)) {
                $param[$key] = unsGenSign($value);
            }
        }

        //2. 生成以&符链接的key=value形式的字符串
        $paramString = urldecode(http_build_query($param));

        //3. 拼接我们的服务秘钥，并md5加密
        $sign = strtoupper(md5($paramString .'&key='. $this->unsKeys));
        Log::pay_write('***银生宝加密前的参数'.$paramString .'&key='. $this->unsKeys.'加密后的mac值'.$sign);
        return $sign;
    }
    public function payConfirmhua() {
        die;
        try {
            $htype = I('post.htype');

            $customerId = I('post.customer_id', 0, 'int');
            $type = I('post.type', 1, 'int'); //类型 1还款 2交首付
            if($type=='') {$type = 1;} //默认还款
            $pay_pass = I('post.pay_pass', '', 'string'); //支付密码(密文)
            $normal_amount = I('post.amount', 0, 'int'); //首付金额,单位分
            $arry = file_get_contents('php://input');
            $arr = json_decode($arry,true);
            $consume_id = $arr['consume_data'][0]['consume_id'];
            $check_pass = I('post.check_pass', 'yes', 'string'); //是否检查密码
            if($check_pass=='') {$check_pass = 'yes';} //是否检查密码默认检查

            $pay_action = I('post.pay_action', 1, 'int'); //还款方式 1用户手动 2系统代扣

            $repay_date = I('post.repay_date', '', 'string'); //最迟还款日
            //$overdue_amount = I('post.overdue_amount', 0, 'int'); //所还逾期金额,单位分
            //首付金额计算
            $overdue_amount = 0; //首付没有逾期金
            $amount = $normal_amount + $overdue_amount; //实付金额

            $order_type = 2; //首付是按单笔还
            $consume_data_arr = array();
            $consume_data_json = '';
            $redis = new Redis();
            Log::pay_write('*********最新*用户还款入参：'.json_encode(I('post.')));
            $futype = M('ConsumeHistory')->where(['id'=>$consume_id,'type'=>5,'status'=>3])->find();//----5--3---
            if ($futype){
                Log::pay_write('*******订单已完成');
                Log::pay_write('**********订单已完成|');
                BusinessException::throwException('订单已完成');
            }

            $key='repay-request'.$consume_id;
            if($redis->get($key)){
                Log::pay_write('***处理中****|异常|订单正在处理中|redis|key：'.$key);
                BusinessException::throwException('订单正在处理中');
            }
            //还款金额计算
            if($type == 1) {
                $consume_data = I('post.consume_data'); //还款入参
                $consume_data_json = ($consume_data) ? json_encode($consume_data) : '';
                $consume_data_arr = $consume_data;

                if($consume_data_arr) {
                    $consume_data_count = count($consume_data_arr);
                    $order_type = ($consume_data_count >1) ? 1: 2;
                    $normal_amount = 0;
                    $overdue_amount = 0;
                    $overdue_amount_all = 0;
                    foreach($consume_data_arr as $v) {
                        if($v['type']==1) {
                            $normal_amount = $normal_amount + $v['amount'];
                            $overdue_amount_all = $overdue_amount_all + $v['overdue_amount'];
                        }
                        if($v['type']==5) {
                            if($v['installment_history']) {
                                foreach($v['installment_history'] as $v1) {
                                    $normal_amount = $normal_amount + $v1['amount'];
                                    $overdue_amount_all = $overdue_amount_all + $v1['overdue_amount']; //逾期金额客户端传值
                                    $this->get_overdue_amount51($v1['id'],$customerId); //逾期情况用户申请额度处理
                                }
                            }
                        }

                        if($v['type']==2 ) {
                            if($v['installment_history']) {
                                $big_id = $v['consume_id'];
                                $small_id = '';
                                foreach($v['installment_history'] as $v1) {
                                    $overdue_amount = $overdue_amount + $v1['overdue_amount'];
                                    $small_id .= $v1['id'].",";
                                }
                                $small_id = substr($small_id, 0, -1);
                                $repay_amount = D('ConsumeHistory')->PaymentCheck($big_id,$small_id); //还款金额外部计算，已包含逾期
                                $normal_amount = $normal_amount + $repay_amount;
                            }
                        }
                    }
                    $amount = $normal_amount + $overdue_amount_all;
                    /***************************增加预期50元*****************************/
                    if($overdue_amount_all>0&&$pay_action==1){
                        $amount=$amount+Constant::OVER_DATE_RATE;
                    }
                    /***************************增加预期50元*****************************/
                } else {
                    BusinessException::throwException(Constant::INVALID_PARAMETER);
                }
            }

            $pay_type = I('post.paytype', 1, 'int'); //支付方式 1联动优势 2微信APP支付
            if($pay_type=='') {$pay_type = 1;} //默认联动优势

            $userinfo = D('Customer')->has($customerId);
            $mobile = $userinfo['mobile'];
            $mer_date = date('Ymd');
            $order_id = $this->trade_no();
            $balance_amount_old = $userinfo['balance_amount'];
            $balance_cash_amount_old = $userinfo['balance_cash_amount'];
            $credit_level_old = $userinfo['credit_level'];

            if($check_pass<>'no') {
                /***|打开支付密码校验|***/
                $userData_=M('Customer')->field('id,pay_pass')->where(['id'=>$customerId])->find();
                //验证支付密码
                if (!$userData_['pay_pass']) {
                    Log::pay_write('+++++++++payConfirm未设置支付密码+++++++++');
                    BusinessException::throwException(Constant::UNSET_PAY_PASS);
                }
                if (password_unmatched($pay_pass, $userData_['pay_pass'])) {
                    Log::pay_write('+++++++++payConfirm支付密码校验失败+++++++++');
                    BusinessException::throwException(Constant::PAY_PASS_UNMATCHED);
                }
                //Log::pay_write('+++++++++payConfirm支付密码校验成功+++++++++');
                /***|打开支付密码校验|***/
            }

            //获取用户绑定卡的支付协议号
            $CustomerBankInfo = M('CustomerBankInfo');
            $data_arr = $CustomerBankInfo->where("customer_id = $customerId and sub_contract_id<>''")->field('sub_contract_id')->find();
            /***************************绑定多张银行卡|finishmodel|customerbanckinfo|**********************/
            $data_arr = $CustomerBankInfo->where("customer_id = $customerId and sub_contract_id >0 and is_default=1")->field('sub_contract_id,card_user_name')->find();
            /***************************绑定多张银行卡|finishmodel|customerbanckinfo|**********************/

            $subContractId = $data_arr['sub_contract_id'];
            if ($subContractId =='') {
                BusinessException::throwException('请先绑定银行卡');
            }
            /*****************************给用户打款操作|本人银行卡校验|************************************/
            //持卡人姓名：$recv_user_name非系统用户本人
            Log::pay_write("*****************payConfirm用户真实姓名：".$userinfo['real_name']."|持卡人姓名：".$data_arr['card_user_name']."|*****：");

            if($userinfo['real_name']!=$data_arr['card_user_name']){
                BusinessException::throwException('持卡人必须是本人');
            }
            //还款 入参金额检查
            if ($consume_data_arr && $type==1) {
                foreach($consume_data_arr as $v) {
                    $consume_id = $v['consume_id'];
                    $normal_amount = $v['amount'];
                    $repay_date = $v['repay_date'];
                    $consumeHistory = M('ConsumeHistory')->where(['id' => $consume_id])->find();

                    if (!$consumeHistory) {
                        BusinessException::throwException(Constant::INVALID_PARAMETER);
                    }
                    //次月
                    if ($normal_amount != $consumeHistory['amount'] && $consumeHistory['type']==1) {
                        BusinessException::throwException(Constant::INVALID_PARAMETER);
                    }
                    if ($consumeHistory['status']==3 && $consumeHistory['type']==1) {
                        BusinessException::throwException(Constant::INVALID_PARAMETER);
                    }
                    //分期
                    if($consumeHistory['type']==2  || $consumeHistory['type']==5) {
                        if($v['installment_history']) {
                            $ConsumeInstallmentHistory =D('ConsumeInstallmentHistory');
                            foreach($v['installment_history'] as $v1) {
                                $id = $v1['id'];
                                $normal_amount = $v1['amount'];
                                $repay_date = $v1['repay_date'];
                                //$repayment_time = strtotime(date('Y-m-' . Constant::BILL_LAST_DAY . ' 00:00:00', time()));
                                $repayment_time = ($repay_date<>'') ? strtotime($repay_date." 00:00:00") : strtotime(date('Y-m-' . Constant::BILL_LAST_DAY . ' 00:00:00', time()));
                                $data_arr = $ConsumeInstallmentHistory->where(['parent_id' => $consume_id,'repayment_time'=>$repayment_time])->field('amount,status')->find();
//                                if ($normal_amount != $data_arr['amount'] && $data_arr['amount']>0) {
//                                    BusinessException::throwException(Constant::INVALID_PARAMETER);
//                                }
                                if ($data_arr['status']==1) {
                                    BusinessException::throwException(Constant::INVALID_PARAMETER);
                                }
                            }
                        }
                    }
                }
                //还多笔
                if($order_type==1) {
                    $consume_id = 0;
                    $repay_date = '';
                }
            }
            if ($amount==0) {
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            $consume_amount = M('ConsumeHistory')->field('consume_amount')->where(['id'=>$consume_id])->find();
            $conamount = $consume_amount['consume_amount'];
            $ben_amount=$consume_amount['consume_amount'];
            if ($amount > $conamount*2){
                $amount = $conamount*2;
            }
            if($htype==2){//逾期客户划扣本金
                $amount=$ben_amount;
                Log::pay_write($customerId.'htype 2 划扣本金'.$amount);
            }else if($htype==3){//逾期客户划扣到账金额
                $money = M('ConsumeHistory')->field('amount')->where(['id'=>$consume_id])->find();
                $amount=$money['amount'];
                Log::pay_write($customerId.'htype 3 划扣到账金额'.$amount);
            }
            $CustomerBillPayLog = M('CustomerBillPayLog');
            //入库
            $data = array(
                'order_id' => $order_id,
                'order_type' => $order_type,
                'customer_id' => $customerId,
                'consume_id' => $consume_id,
                'consume_data' => $consume_data_json,
                'repay_date' => $repay_date,
                'amount' => $amount,
                'trade_id' => '',
                'pay_type' => $pay_type,
                'type' => $type,
                'balance_amount_old' =>$balance_amount_old,
                'balance_cash_amount_old' =>$balance_cash_amount_old,
                'overdue_amount' => $overdue_amount,
                'pay_action' => $pay_action,
            );

            $CHrepay = M("ConsumeHistory")->where("id = $consume_id and repay = 1 ")->find();
            $repay_add_time = time() - $CHrepay['repay_add_time'];
            $repay_add_time = ($repay_add_time < 1800) ? true : false ;
            if ( $repay_add_time ) {
                if ( $CHrepay ) {
                    Log::pay_write('**********该笔消费订单|'. $consume_id .'|：'.'throwException(支付订单中)');
                    BusinessException::throwException('支付订单中');
                }
            }

            if (false === ($insertId = $CustomerBillPayLog->add($data))) {
                // if (false === ($insertId = $_result )) {
                BusinessException::throwException('支付订单创建失败');
            }

            if ($customerId == "2162"){
                $uns_amount = 400.00;//测试写死1分钱
            }else {
                $uns_amount = $amount * 0.01;
            }

            /***********************还款校验|******************************************/
            $pay_check=M('ConsumeHistory')->where(['id'=>$consume_id,'type'=>'5','status'=>'3'])->find();
            if($pay_check){
                Log::pay_write('**********该笔消费已还款|pay_check|：'.json_encode($pay_check));
                BusinessException::throwException('该笔消费已还款，请勿重复还款~');
            }
            /***********************还款校验|******************************************/
            Log::pay_write('**********用户还款金额：'.$uns_amount);
            Log::pay_write('**********用户还款订单号：'.$order_id);
            Log::pay_write('**********用户还款卡号子协议：'.$subContractId);
            $result = $this->unsPayhua($subContractId,$order_id,$uns_amount);
            Log::pay_write(' 后台划扣实际金额payConfirmhua consume_id：'.$consume_id.'set********repay=>1******start'.'  '.$subContractId.'    '.$order_id.'   '.$uns_amount);
            $repayStatus = M("ConsumeHistory")->where("id = $consume_id")->setField(array('repay'=>1, 'repay_add_time'=>time()));
            Log::pay_write('**********consume_id：'.$consume_id.'设置结果********repay:'. ($repayStatus ? 1 : 0) );
            /**********************处理中订单|**********************************/
            $key='repay-request'.$consume_id;
            if (!$redis->get($key)){
                $key='repay-request'.$consume_id;
                $redis_res=$redis->set($key,$consume_id,1800);//处理中的订单|---测试下---失效时间设置小---|第一次|控制住|第二次|允许|
                Log::pay_write('*-----******|订单号码：'.$order_id.'|查询用户是否实际还款返回结果|存入redis结果|'.json_encode($redis_res));
                Log::pay_write('**********|订单号码：'.$order_id.'|存入redis|key:'.$key.'|value:'. $redis_res=$redis->get($key));
            }
            /**********************处理中订单|**********************************/

            Log::pay_write('**********用户还款执行返回结果：'.json_encode($result));

            if($result) {
                $ret_code = $result['result_code'];
                $ret_msg = '';
                $trade_state = $result['result_msg'];

                if($ret_code=='0000') {
                    Log::pay_write('**********查询用户是否实际还款：'.json_encode($result));
                    //查询是否还款成功
                    $resultstatu = $this->unsPaystatu($order_id);
                    Log::pay_write('**********查询用户是否实际还款返回结果status：'.$resultstatu['status']);
                    Log::pay_write('**********查询用户是否实际还款返回结果：desc:'.$resultstatu['desc']);
                    Log::pay_write('**********查询用户是否实际还款返回结果：result_msg:'.$resultstatu['result_msg']);
                    Log::pay_write('**********查询用户是否实际还款返回结果status：'.$resultstatu['status']);
                    Log::pay_write('**********查询用户是否实际还款返回结果：desc:'.$resultstatu['desc']);
                    Log::pay_write('**********查询用户是否实际还款返回结果：result_msg:'.$resultstatu['result_msg']);

                    if($resultstatu['status'] == '00'){
                        Log::pay_write('**********查询用户'.$order_id.'是否实际还款返回结果status：00|成功');
                        //还款成功写库
                        //$sqldata = array('trade_state'=>$trade_state,'ret_code'=>$ret_code,'status'=>2);
                        $sqldata = array('trade_state'=>$trade_state,'ret_msg'=>'success','pay_time'=>time(),'ret_code'=>$ret_code,'status'=>2);
                        $CustomerBillPayLog->where(['id'=>$insertId,'status'=>0])->setField($sqldata);
                        $ret = Constant::getReturn(Constant::SUCCESS);
                        $ret['data'] = array('order_id'=>$order_id,'trade_no'=>$order_id,'amount' => $amount,'pay_action' => $pay_action,'customer_id' => $customerId,'pay_time' => date('Y-m-d H:i:s',time()));

                        //更新订单状态到已还款完成
                        M('ConsumeHistory')->where(['id'=>$consume_id])->setField(['status'=>3,'update_time'=>time()]);
                        M('Customer')->where(['id'=>$customerId])->setField(['cash_amount'=>0]);
                        M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id,'update_time'=>0])->setField(['status'=>1,'update_time'=>time(),"final_amount"=>0]);
                        //M('Customer')->where(['id'=>$customerId])->setField(['cash_amount'=>0]);

                        /****这里扣款成功修改status给贷后分单用，防止撤单分单出现已还款仍能撤分单***/
                        $ConsumeUserInfo = M('consume_user')->where("consume_id = $consume_id and status = 1")->find();
                        if (isset($ConsumeUserInfo) && !empty($ConsumeUserInfo)) {
                            $ConsumeUserStatusInfo = M('consume_user')->where("consume_id = $consume_id and status = 1")->setField(array('status'=>2));
                        }
                        // 目前bochen要撤单不分回款未回款，目前无条件撤回,所以这里不做状态改变，打开则为做了状态改变
                        /****这里扣款成功修改status给贷后分单用，防止撤单分单出现已还款仍能撤分单***/

                    }else if($resultstatu['status'] == '20'){
                        Log::pay_write('**********查询用户'.$order_id.'是否实际还款返回结果status：20|余额不足');
                        $status = 3;
                        $sqldata = array('ret_msg'=>'银行卡余额不足','ret_code'=>1111,'status'=>$status);
                        $CustomerBillPayLog->where(['id'=>$insertId,'status'=>0])->setField($sqldata);
                        //手动输入的预扣金额为零
                        M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id,'update_time'=>0])->setField(["final_amount"=>0]);
                        $this->ajaxReturn(['code' => 1111, 'msg' => '银行卡上余额不足']);
                        /********************************还款处理中**************************************/

                    }elseif($resultstatu['status'] == '10'){
                        Log::pay_write('**********|订单号码：'.$order_id.'|查询用户是否实际还款返回结果|：还款处理中');

                        $this->ajaxReturn(['code' => 10, 'msg' => '正在还款，请稍后']);
                    }
                } else if($ret_code=='1111') {
                    //付款提交失败
                    $status = 3;
                    $sqldata = array('ret_msg'=>$trade_state,'ret_code'=>$ret_code,'status'=>$status);
                    $CustomerBillPayLog->where(['id'=>$insertId,'status'=>0])->setField($sqldata);
                    //手动输入的预扣金额为零
                    M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id,'update_time'=>0])->setField(["final_amount"=>0]);
                    $this->ajaxReturn(['code' => $ret_code, 'msg' => $trade_state]);
                }else {
                    //付款提交失败
                    $status = 3;
                    $ret_msg2 ="提交付款失败";
                    $ret_code2 = 1112;
                    $sqldata = array('ret_msg'=>$trade_state,'ret_code'=>$ret_code,'status'=>$status);
                    $CustomerBillPayLog->where(['id'=>$insertId,'status'=>0])->setField($sqldata);
                    //手动输入的预扣金额为零
                    M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id,'update_time'=>0])->setField(["final_amount"=>0]);
                    BusinessException::throwException($ret_code2.$ret_msg2);
                }
            }else{
                $key='repay-request'.$consume_id;
                if($redis->get($key)){
                    $redis->rm($key);
                    BusinessException::throwException('该笔消费支付失败~');
                    Log::pay_write("测试失败情况异步通知结果|订单".$order_id."|删除redis处理中|key:".$key.'|');
                }
            }
        } catch (BusinessException $e) {
            $this->ajaxReturn(['code' => $e->getCode(), 'msg' => $e->getMessage(),'data'=>['amount'=>$amount,'customerId'=>$customerId]]);
        }
        Response::format($ret);
        $this->ajaxReturn($ret);
    }
    public function unsPayhua($subContractId,$orderId,$amount) {
        $url = $this->unsRequestHost.'/unspay-external/delegateCollect/collect';
        $xml_data = array(
            'accountId'=>$this->unsAccountId,
            'subContractId'=>$subContractId, //1279789
            'orderId'=>$orderId, //14881805185186
            'purpose'=>'消费分期还款',
            'amount'=>$amount, //0.01
            /*'phoneNo'=>'18634364997', //银行预留手机号*/
            'responseUrl'=>$this->unsResponseHost.'/Home/Pay/unsNotifyhua',
        );

        $sign = $this->unsGenSign($xml_data);
        $xml_data['mac'] = $sign;
        $xml_data = http_build_query($xml_data);
        Log::pay_write('**********用户实际还款参数：'.$xml_data);
        Log::pay_write('**********用户实际还款url：'.$url);
        $result = $this->unsCurlPost($url,$xml_data);
        Log::pay_write('**********用户实际还款执行结果：'.$result);
        $result_arr = json_decode($result,true);
        //{"result_code":"0000","result_msg":"交易成功"}
        return $result_arr;
        //exit;
    }
    public function unsNotifyhua() {
        $check_mac = strtoupper(md5("accountId=".$this->unsAccountId."&orderId=".$_POST['orderId']."&amount=".$_POST['amount']."&result_code=".$_POST['result_code']."&result_msg=".$_POST['result_msg']."&key=".$this->unsKeys.""));
        $mac = $_POST['mac'];
        if($mac==$check_mac) {
            Log::write("银生宝代扣异步通知结果:success", Log::INFO);
            $ret_msg = $_POST['result_msg'];
            $ret_code = $_POST['result_code'];
            $CustomerBillPayLog = M('CustomerBillPayLog');
            $order_id = $_POST['orderId'];
            /************************/
            $redis = new Redis();
            /************************/
            if($ret_code=='0000') {

                $sqldata = array('ret_msg'=>'success','pay_time'=>time(),'status'=>1);
                $CustomerBillPayLog->where(['order_id'=>$order_id,'pay_time'=>0])->setField($sqldata);

                $CustomerBillPayLogInfo = $CustomerBillPayLog->where(['order_id' => $order_id])->find();
                $consume_id = $CustomerBillPayLogInfo['consume_id'];
                $customer_id = $CustomerBillPayLogInfo['customer_id'];

                if($consume_id>0) {
                    /****这里扣款成功修改status给贷后分单用，防止撤单分单出现已还款仍能撤分单***/
                    $ConsumeUserInfo = M('consume_user')->where("consume_id = $consume_id and status = 1")->find();
                    if (isset($ConsumeUserInfo) && !empty($ConsumeUserInfo)) {
                        $ConsumeUserStatusInfo = M('consume_user')->where("consume_id = $consume_id and status = 1")->setField(array('status'=>2));
                    }
                    /****这里扣款成功修改status给贷后分单用，防止撤单分单出现已还款仍能撤分单***/
                    Log::pay_write('**********银生宝定时划扣异步通知|订单|'.$order_id.'|成功');
                    /********************异步通知结果***************/
                    //M('ConsumeHistory')->where(['id'=>$consume_id,'update_time'=>0])->setField(['status'=>3,'update_time'=>time()]);
                    $test_consume=M('ConsumeHistory')->where(['id'=>$consume_id,'type'=>5,'status'=>1])->setField(['status'=>3,'update_time'=>time()]);
                    $test_install=M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->setField(['status'=>1,'update_time'=>time()]);
                    $trd=M('Customer')->where(['id'=>$customer_id])->setField(['balance_cash_amount'=>200000,'cash_amount'=>0]);
                    Log::pay_write('**********银生宝定时划扣异步通知|操作ConsumeHistory|结果：'.json_encode($test_consume).'|');
                    Log::pay_write('**********银生宝定时划扣异步通知|ConsumeInstallmentHistory|结果：'.json_encode($test_install).'|');
                    Log::pay_write('**********银生宝定时划扣异步通知|Customer|结果：'.json_encode($trd).'|');
                    Log::pay_write('**********银生宝定时划扣异步通知|订单|'.$order_id.'|成功');
                    /**********************处理中*************************/
                    //查询用户订单信息
                    $consume = M('ConsumeHistory')->where(['id'=>$consume_id])->find();
                    $customerid = $consume['customer_id'];
                    $mobiles = M('Customer')->field('mobile')->where(['id'=>$customerid])->find();
                    if (!empty($mobiles)){
                        $mobile = $mobiles['mobile'];
                        /*云峰开始|使用请直接打开注释|并注释掉上边的发送代码*/
                        $content = "【找钱花】尊敬的找钱花客户，您的还款系统划扣已成功，祝您生活愉快";
                        $ret = SendSMS::yunfeng_send_json($mobile,$content);
                        Log::borrow_write("+++++++++新版自动划扣短信---手机号:".$mobile."发短信结果".json_encode($ret), Log::DEBUG);
                    }
                    $CustomerBillPayLogInfo = $CustomerBillPayLog->where(['order_id' => $order_id])->find();
                    $key='repay-request'.$CustomerBillPayLogInfo['consume_id'];
                    if($redis->get($key)){
                        $redis_res=$redis->rm($key);
                        Log::pay_write("银生宝定时划扣异步通知结果|订单".$order_id."|删除redis处理中|key:".$key.'|');
                        Log::pay_write("银生宝定时划扣异步通知结果订单".$order_id."|删除redis处理中的结果|".$redis_res.'|');
                    }
                    Log::pay_write("银生宝定时划扣异步通知结果||order_id:".$order_id.'|成功');
                    /**********************处理中*************************/
                }
            } else {
                $CustomerBillPayLogInfo = $CustomerBillPayLog->where(['order_id' => $order_id])->find();
                $consume_id = $CustomerBillPayLogInfo['consume_id'];
                $repayStatus = M('ConsumeHistory')->where(['id'=>$consume_id])->setField(['repay'=>0, 'repay_add_time'=>0]);
                Log::pay_write("订单".$consume_id."银生宝定时划扣异步ConsumeHistory设置repay通知结果||repay:". ($repayStatus ? 0 : 1) .'|');
                //$ret_msg = 'fail';
                $sqldata = array('ret_msg'=>$ret_msg,'ret_code'=>$ret_code);
                $CustomerBillPayLog->where(['order_id'=>$order_id,'pay_time'=>0])->setField($sqldata);
                /**********************处理中*************************/

                $CustomerBillPayLogInfo = $CustomerBillPayLog->where(['order_id' => $order_id])->find();
                $key='repay-request'.$CustomerBillPayLogInfo['consume_id'];
                if($redis->get($key)){
                    $redis_res=$redis->rm($key);
                    Log::pay_write("银生宝代扣异步通知结果|订单".$order_id."|删除redis处理中|key:".$key.'|');
                    Log::pay_write("银生宝代扣异步通知结果|订单".$order_id."|删除redis处理中的结果|".$redis_res.'|');
                }
                Log::pay_write("银生宝定时划扣异步通知结果||order_id:".$order_id.'|失败');
                /**********************处理中*************************/
            }

            echo 'success';
        }
    }
    //请求交易中心划扣跳转
    public function payConfirmPart($customer_id,$consume_id,$amount,$repay_date,$kind,$typeof){
//        $customer_id = I('get.customer_id');
//        $amoun = I('get.amount');
//        $repay_date = I('get.repay_date');
        $bank = $this->getDefaultCard($customer_id);
        $customer = M('Customer')->field('id_num')->where(['id'=>$customer_id])->find();
        $consume = M('ConsumeHistory')->where(['id'=>$consume_id])->select();
        Log::pay_write("payConfirmPart--用户ID".$customer_id."********订单信息".json_encode($consume)."**********用户信息".json_encode($customer));
        if ($consume[0]['type'] == 5 && $consume[0]['status'] == 1 && $consume[0]['repay'] == 0){
            $url = "http://zqhfundtest.huoyanzichan.com/RepayMoney/Pay/consumePayRequest";
            $data = [];
            $data['sub_contract_id'] = $bank['sub_contract_id'];
            $data['real_name'] = $bank['card_user_name'];
            $data['card_num'] = $bank['card_num'];
            $data['reser_phone'] = $bank['reserved_mobile'];
            $data['id_card_no'] = $customer['id_num'];
            if ($bank['gate_id'] == 'ABC'){
                $data['source'] = 1;
            } else {
                $data['source'] = 2;
            }
//            $data['source'] = $bank['source']?$bank['source']:1;
            $data['type'] = 1;
            $data['customer_id'] = $customer_id;
            $data['consume_id'] = $consume_id;
            $data['amount'] = $amount/100;
            $data['callback_url'] = "http://api1.huoyanzichan.com/Home/Pay/huakouhuidiaos";
            $data['trade_no'] = $this->trade_no();
            $data['pay_type'] = $kind;
            $data['typeof'] = $typeof?$typeof:0;
            $CustomerBillPayLog = M('CustomerBillPayLog');
            Log::pay_write("脚本划扣参数".json_encode($data)."用户".$customer_id);
            $ress = D('Ajax')->ajaxPosts($url,$data);
            $res = json_decode($ress,true);
            Log::pay_write("payConfirmPart交易中心".$data['consume_id']."返回结果     ".$res['code']."    ".json_encode($res));
            if ($res['code'] == 200){
                $sqldata = ['repay'=>1];
                M('ConsumeHistory')->where(['id'=>$data['consume_id']])->save($sqldata);
                Log::pay_write("payConfirmPart  交易中心".$data['consume_id']."接受请求返回结果成功 ".json_encode($res));
                //入库
                $datass = array(
                    'order_id' => $data['trade_no'],
                    'order_type' => 1,
                    'customer_id' => $customer_id,
                    'consume_id' => $consume_id,
                    'consume_data' => json_encode($data),
                    'repay_date' => date("Y-m-d",$repay_date),
                    'amount' => $amount,
                    'trade_id' => '',
                    'pay_type' => 1,
                    'type' => 1,
                    'balance_amount_old' =>'',
                    'balance_cash_amount_old' =>'',
                    'overdue_amount' => '',
                    'pay_action' => 2,
                );
                if (false === ($insertId = $CustomerBillPayLog->add($datass))) {
                    BusinessException::throwException('支付订单创建失败');
                }
                $rea = ['code'=>200];
                echo json_encode($rea);return;
            } else {
                Log::pay_write("payConfirmPart 交易中心".$data['consume_id']."接受请求返回结果失败   orderid ".$data['consume_id']."+++++++".json_encode($res));
                $rea = ['code'=>400];
                echo json_encode($rea);return;
            }
        } else {
            Log::pay_write("payConfirmPart 此订单不能划扣".$consume_id);
            return false;
        }
    }
    /**
     * 交易中心判断代扣能否进行
     */
    public function queryPayment(){
        $result = file_get_contents('php://input');
        $result = json_decode($result,true);
        Log::pay_write("询问是否能进行还款接受参数".json_encode($result));
//        $order_id =   $result['trade_no'];
        $amount =  $result['amount'];
        $consumeId =  $result['consume_id'];
        $customerId =  $result['customer_id'];
//        $type =  $result['type'];
//        if ($type == 1){
//            $key = "请求交易中心代扣".$customerId;
//        } else if ($type == 2){
//            $key = "请求交易中心续借".$customerId;
//        } else if ($type == 3){
//            $key = "请求交易中心划扣".$customerId;
//        }
//        $redis = new Redis();
//        $res = $redis->get($key);
//        $res1 = explode(',',$res);
//        $order_ids = $res1[2];
//        $amounts = $res1[1];
//        $consumeIds = $res1[0];
        $res = M('Customer')->field('id')->where(['id'=>$customerId])->find();
        if ($res){
//            $re = M('ConsumeHistory')->where(['customer_id'=>$customerId])->order('id DESC')->limit(2)->select();
//            if ($re[0]['type'] == 5 && $re[0]['status'] == 1 && $re[1]['type'] == 4 && $re[1]['status'] == 12 && $re[0]['consume_amount'] >= $amount/2 && $re[0]['repay'] == 0){
            Log::pay_write("询问接受参数 成功".' '.$customerId.'  '.$consumeId);
            $ret = ['code'=>200,'msg'=>"success"];
//            } else {
//                Log::pay_write("询问接受参数 失败".' 客户id'.$customerId.'  订单id'.$consumeId."    ".json_encode($re));
//                $ret = ['code'=>400,'msg'=>"failed"];
//            }
        } else {
            Log::pay_write("询问接受参数 失败".' 客户id'.$customerId.'  订单id'.$consumeId);
            $ret = ['code'=>4001,'msg'=>"failed"];
        }
        $this->ajaxReturn($ret);
    }
    //新版获取银行卡
    public  function  getDefaultCard($customer_id){
        //新的表
        $map = [];
        $map['customer_id'] = $customer_id;
        $map['is_default'] = 1;
        $newlists = M('customer_bank_info_new',null)
            ->field('customer_id,card_user_name,sub_contract_id,
                    card_num,reserved_mobile,usr_busi_agreement_id,
                    usr_pay_agreement_id,gate_id,bank_card_type,
                    is_default,source,bank_address')
            ->where($map)
            ->find();
        if($newlists){//new  table  has user data
            return $newlists;
        }else{//new table  does not have any data  ,turn to our old table
            //新表旧表未同步之前 需要保证用户可以取到之前的老数据
            $oldlists = M('customer_bank_info',null)
                ->field('customer_id,card_user_name,sub_contract_id,
                    card_num,reserved_mobile,usr_busi_agreement_id,
                    usr_pay_agreement_id,gate_id,bank_card_type,
                    is_default,bank_address')
                ->where($map)
                ->find();
            if($oldlists){
                Log::borrow_write("获取用户主卡".json_encode($oldlists)."    用户".$customer_id);
                return $oldlists;
            }else{
                return  false;
            }
        }
    }
    //交易中心划扣异步回调
    public function huakouhuidiaos(){
        Log::pay_write("这就是为了统计数量的");
        $resultstatu = file_get_contents('php://input');
        $resultstatu = json_decode($resultstatu,true);
        Log::pay_write("huakouhuidiaos用户还款交易中心回调接收数据     ".json_encode($resultstatu));
        $CustomerBillPayLog = M('CustomerBillPayLog');
        $ret_code = $resultstatu['result_code'];
        $ret_msg = $resultstatu['result_msg'];
        $trade_state = $resultstatu['trade_state'];
        $order_id = $resultstatu['trade_no'];
        $amount = $resultstatu['amount']*100;
        $customerId = $resultstatu['customer_id'];
        $consume_id = $resultstatu['order_no'];
        $kind = $resultstatu['pay_type'];
        $typeof = $resultstatu['typeof'] == ''?0:$resultstatu['typeof'];
        $panduanmsg = $CustomerBillPayLog->field('ret_msg')->where(['order_id'=>$order_id])->find();
        if (!empty($panduanmsg['ret_msg'])){
            Log::pay_write("此订单号".$order_id."已经处理了，这块不做处理直接返回");
            return;
        }
        if($resultstatu['code'] == 200){
            $url = "http://zqhfundtest.huoyanzichan.com/RepayMoney/Pay/testSearch?requestno=".$order_id;
            $resultes = file_get_contents($url);
//            echo $resultes;
            $resulte = json_decode($resultes,true);
            Log::pay_write("当前订单查询结果".json_encode($resulte)."查询url".$url."实际返回结果".$resultes);
            if ($resulte['status'] == 'PAY_SUCCESS'){
                Log::pay_write('*huakouhuidiaos查询用户'.$order_id.'是否实际还款返回结果status：200     huakouhuidiaos划扣成功');
                //还款成功写库
                $ret_code = $ret_code?$ret_code:'0000';
                $sqldata = array('ret_msg'=>'success','pay_time'=>time(),'ret_code'=>$ret_code,'status'=>1);
                Log::pay_write('huakouhuidiaos查询用户'.$customerId.'订单号'.$order_id.'是否实际还款返回结果status：200|成功'.json_encode($sqldata));
                $CustomerBillPayLog = M('CustomerBillPayLog');
                $res = $CustomerBillPayLog->where(['order_id'=>$order_id])->save($sqldata);
                Log::pay_write('huakouhuidiaos查询用户'.$customerId.'订单号'.$order_id.'是否实际还款返回结果status：200|成功'.$CustomerBillPayLog->getLastSql()."执行结果".$res);
//            $ret = Constant::getReturn(Constant::SUCCESS);
//            $ret['data'] = array('order_id'=>$order_id,'trade_no'=>$order_id,'amount' => $amount,'pay_action' => $pay_action,'customer_id' => $customerId,'pay_time' => date('Y-m-d H:i:s',time()));
                if ($kind == '3'){
                    Log::pay_write("huakouhuidiaos-用户部分还款开始  ".$customerId."    回调数据   ".json_encode($resultstatu));
                    M('ConsumeHistory')->where(['id'=>$consume_id,'type'=>5,'status'=>1])->setField(['typeof'=>$typeof]);
                    $res = M('ConsumeHistory')->field('part_need_pay_amount,part_pay_amount,consume_amount,repayment_time,update_time')->where(['id'=>$consume_id,'type'=>5,'status'=>1])->find();
                    $part_pay_amount = $amount + $res['part_pay_amount'];
                    $data1 = date("Y-m-d H:i:s", time());
                    $data4 = date("Y-m-d", time());
                    $data2 = date("Y-m-d H:i:s", $res['repayment_time']);
                    $data3 = date("Y-m-d", $res['update_time']);
                    $date = floor((strtotime($data1) - strtotime($data2)) / 86400);
                    $date1 = (strtotime($data4) - strtotime($data3)) / 86400;
                    if ($part_pay_amount < $res['consume_amount']){
                        if ($res['update_time'] == 0) {
                            $num = ($res['consume_amount'] - $res['part_pay_amount']) * Constant::Overdue_Interest_Rate * $date;
                            if (($num + Constant::OVER_DATE_RATE) > $res['consume_amount']){
                                $num = $res['consume_amount'] - Constant::OVER_DATE_RATE;
                            }
                            $part_need_pay_amount = $num + $res['consume_amount'] - $amount;
                        } else {
                            $num = ($res['consume_amount'] - $res['part_pay_amount']) * Constant::Overdue_Interest_Rate * $date1 + $res['part_need_pay_amount'];
                            $yihuan = $res['part_pay_amount'];
                            if (($num + $yihuan + Constant::OVER_DATE_RATE) > $res['consume_amount'] * 2){
                                $num = ($res['consume_amount'] * 2) - $yihuan - Constant::OVER_DATE_RATE;
                            }
                            $part_need_pay_amount = $num - $amount;
                        }
                        Log::pay_write('划扣--本金未还完   '.$customerId.'剩余还款金额 '.$part_need_pay_amount);
                    } else {
                        if ($res['part_need_pay_amount'] == 0){
                            $num = ($res['consume_amount'] - $res['part_pay_amount']) * Constant::Overdue_Interest_Rate * $date;
                            if (($num + Constant::OVER_DATE_RATE) > $res['consume_amount']){
                                $num = $res['consume_amount'] - Constant::OVER_DATE_RATE;
                            }
                            $part_need_pay_amount = $num + $res['consume_amount'] - $amount;
                        } else {
                            $part_need_pay_amount = $res['part_need_pay_amount'] - $amount;
                        }
                        Log::pay_write('划扣--本金已还完   '.$customerId.'剩余还款金额 '.$part_need_pay_amount);
                    }
                    Log::pay_write("huakouhuidiaos".$customerId."最后数据   ".$part_need_pay_amount);
                    if ($part_need_pay_amount < 0){
                        $part_need_pay_amount = 0;
//                    $part_pay_amount = $part_pay_amount + Constant::OVER_DATE_RATE;
                    }
                    Log::pay_write("huakouhuidiaos".$customerId."最后数据".$part_need_pay_amount."   填写金额   ".$part_pay_amount);
                    M('ConsumeHistory')->where(['id'=>$consume_id,'type'=>5,'status'=>1])->setField(['part_need_pay_amount'=>$part_need_pay_amount,'part_pay_amount'=>$part_pay_amount,'update_time'=>time(),'repay'=>0]);
                    if ($part_need_pay_amount == 0){
                        Log::pay_write("huakouhuidiaos".$customerId."  该用户（多次部分还款）贷款已结清");
                        $mobiles = M('Customer')->field('mobile,real_name')->where(['id'=>$customerId])->find();
                        if (!empty($mobiles)){
                            $res = M('ConsumeHistory')->field('consume_amount,add_time')->where(['id'=>$consume_id,'type'=>5,'status'=>1])->find();
                            $mobile = $mobiles['mobile'];
                            /*云峰开始|使用请直接打开注释|并注释掉上边的发送代码*/
                            $name = $mobiles['real_name'];
                            $part_pay_amount = $part_pay_amount/100;
                            $amounts = $res['consume_amount']/100;
                            $time = $res['add_time'];
                            $dates = date("Y年m月d日",$time);
                            Log::pay_write("amount".$amounts."时间".$time."最后时间".$dates."sql".M('ConsumeHistory')->getLastSql());
//                        $content = "【找钱花】尊敬的找钱花客户".$name."您好，您于".$dates."的".$amounts."元金额借款，现已成功还款".$part_pay_amount."元。剩余未还金额请尽快还款，以避免产生不必要的逾期费用，若已结清请忽略。感谢您的理解和支持！";
                            //$content = "【找钱花】尊敬的".$name."您好，您于".$dates."的".$amounts."借款，现还款".$part_pay_amount."元。未还清部分请尽快还款，避免产生不必要的逾期费用，若已结清请忽略。";
                            $content = "【找钱花】尊敬的".$name."您好，您于".$dates."的".$amounts."借款，现还款".$part_pay_amount."元。未还清部分请尽快还款，若已结清请忽略。";
                            $ret = SendSMS::yunfeng_send_json($mobile,$content);
                            Log::borrow_write("huakouhuidiaos+++++++++新版部分自动划扣短信---手机号:".$mobile."发短信结果".json_encode($ret).$content);
                        }
                        Log::pay_write("用户部分还款".$customerId."全部还清++++修改状态5-1=>5-3");
                        Log::pay_write("这里是用于统计每次      全部还清划扣成功      用户".$customerId."本次还款".$amount."总共还款".$part_pay_amount);
                        M('ConsumeHistory')->where(['id'=>$consume_id,'type'=>5,'status'=>1])->setField(['status'=>3,'update_time'=>time(),'repay'=>0]);
                        M('Customer')->where(['id'=>$customerId])->setField(['balance_cash_amount'=>200000,'cash_amount'=>0]);
                        M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->setField(['status'=>1,'update_time'=>time(),"final_amount"=>0]);
                        $ConsumeUserInfo = M('ConsumeUser')->where("consume_id = $consume_id and status = 1")->find();
                        if (isset($ConsumeUserInfo) && !empty($ConsumeUserInfo)) {
                            $ConsumeUserStatusInfo = M('ConsumeUser')->where("consume_id = $consume_id and status = 1")->setField(array('status'=>2));
                        }
                        $consume = M('ConsumeHistory')->where(['id'=>$consume_id])->find();
                        if ($consume['status'] == 3){
                            $paylog = $CustomerBillPayLog->where(['order_id'=>$order_id])->find();
                            $consumehistory = M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->find();
                            if ($paylog['amount'] != $consumehistory['amount']){
                                $scredit = D('CustomerAuth')->saveCustomerAuth($consume['customer_id']);
                                if (!$scredit){
                                    BusinessException::throwException(Constant::INVALID_PARAMETER);
                                }
                                $czhima = D('Customer')->saveCustomerzhima($consume['customer_id']);
                                if (!$czhima){
                                    BusinessException::throwException(Constant::INVALID_PARAMETER);
                                }
                            }
                        }
                    } else {
                        Log::pay_write("huakouhuidiaos".$customerId."  该用户贷款部分结清".'已还金额'.$part_pay_amount);
                        $mobiles = M('Customer')->field('mobile,real_name')->where(['id'=>$customerId])->find();
                        Log::pay_write("这里是用于统计每次     部分还清划扣成功     用户".$customerId."本次还款".$amount."总共还款".$part_pay_amount."剩余未还金额".$part_need_pay_amount);
                        if (!empty($mobiles)){
                            $mobile = $mobiles['mobile'];
                            $res = M('ConsumeHistory')->field('consume_amount,add_time,part_need_pay_amount,repayment_time')->where(['id'=>$consume_id,'type'=>5,'status'=>1])->find();
                            /*云峰开始|使用请直接打开注释|并注释掉上边的发送代码*/
                            $name = $mobiles['real_name'];
                            $part_pay_amount = $part_pay_amount/100;
                            $amounts = $res['consume_amount']/100;
                            $time = $res['add_time'];
                            $dates = date("Y年m月d日",$time);
                            Log::pay_write("amount".$amounts."时间".$time."最后时间".$dates."sql".M('ConsumeHistory')->getLastSql());
//                        $content = "【找钱花】尊敬的找钱花客户".$name."您好，您于".$dates."的".$amounts."元金额借款，现已成功还款".$part_pay_amount."元。剩余未还金额请尽快还款，以避免产生不必要的逾期费用。感谢您的理解和支持！";
                            //$content = "【找钱花】尊敬的".$name."您好，您于".$dates."的".$amounts."借款，现还款".$part_pay_amount."元。未还清部分请尽快还款，避免产生不必要的逾期费用。";
                            $content = "【找钱花】尊敬的".$name."您好，您于".$dates."的".$amounts."借款，现还款".$part_pay_amount."元。未还清部分请尽快还款，若已结清请忽略。";
                            $ret = SendSMS::yunfeng_send_json($mobile,$content);
                            Log::borrow_write("huakouhuidiaos+++++++++新版部分自动划扣短信---手机号:".$mobile."发短信结果".json_encode($ret).$content);
                        }
                        if ($res['part_need_pay_amount'] > $amount){
                            //$customer_id,          $amount,          $repay_date,          $kind,          $typeof
                            $repay_date = $res['repayment_time'];
                            $num = $res['part_need_pay_amount'] + Constant::OVER_DATE_RATE - $amount;
                            if ($num < 10000){
                                $am = $res['part_need_pay_amount'] + Constant::OVER_DATE_RATE;
                            } else {
                                $am = $amount;
                            }
                        } else {
                            $repay_date = $res['repayment_time'];
                            $am = $res['part_need_pay_amount'] + Constant::OVER_DATE_RATE;
                        }
                        Log::pay_write("循环划扣    再次请求参数".$customerId."++++".$am."++++".$repay_date."++++".$kind."++++".$typeof);
                        $this->payConfirmPart($customerId,$consume_id,$am,$repay_date,$kind,$typeof);
                    }
                } else {
                    Log::pay_write("huakouhuidiaos".$customerId."   该用户还全款成功");
                    $res = M('ConsumeHistory')->field('part_pay_amount,repayment_time')->where(['id'=>$consume_id,'type'=>5,'status'=>1])->find();
                    $part_pay_amount = $amount + $res['part_pay_amount'];
                    //更新订单状态到已还款完成
                    M('ConsumeHistory')->where(['id'=>$consume_id,'type'=>5,'status'=>1])->setField(['status'=>3,'update_time'=>time(),'part_pay_amount'=>$part_pay_amount,'part_need_pay_amount'=>0,'repay'=>0]);
                    M('Customer')->where(['id'=>$customerId])->setField(['balance_cash_amount'=>200000,'cash_amount'=>0]);
                    M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->setField(['status'=>1,'update_time'=>time(),"final_amount"=>0]);
                    $mobiles = M('Customer')->field('mobile')->where(['id'=>$customerId])->find();
                    if (!empty($mobiles)){
                        $mobile = $mobiles['mobile'];
                        $timecha = $res['repayment_time'];
                        $day1=strtotime(date("Y-m-d 23:59:59",time()))-86400;//逾期一天
                        $day2=strtotime(date("Y-m-d 23:59:59",time()))-2592000;//逾期三十天
                        if ($timecha >= $day2 && $timecha <= $day1){
                            $content = "【找钱花】尊敬的找钱花客户，您的逾期借款已经划扣成功，祝您生活愉快";
                        } else {
                            $content = "【找钱花】尊敬的找钱花客户，您的还款系统划扣已成功，祝您生活愉快";
                        }
                        $ret = SendSMS::yunfeng_send_json($mobile,$content);
                        Log::borrow_write("++huakouhuidiaos+++++++新版自动划扣短信---手机号:".$mobile."发短信结果".json_encode($ret), Log::DEBUG);
                    }
                    Log::pay_write("这里是用于统计每次      一次还清划扣成功      用户".$customerId."本次还款".$amount."总共还款".$part_pay_amount);
                    /****这里扣款成功修改status给贷后分单用，防止撤单分单出现已还款仍能撤分单***/
                    $ConsumeUserInfo = M('ConsumeUser')->where("consume_id = $consume_id and status = 1")->find();
                    if (isset($ConsumeUserInfo) && !empty($ConsumeUserInfo)) {
                        $ConsumeUserStatusInfo = M('ConsumeUser')->where("consume_id = $consume_id and status = 1")->setField(array('status'=>2));
                    }
                    $consume = M('ConsumeHistory')->where(['id'=>$consume_id])->find();
                    if ($consume['status'] == 3){
                        $paylog = $CustomerBillPayLog->where(['order_id'=>$order_id])->find();
                        $consumehistory = M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->find();
                        if ($paylog['amount'] != $consumehistory['amount']){
                            $scredit = D('CustomerAuth')->saveCustomerAuth($consume['customer_id']);
                            if (!$scredit){
                                BusinessException::throwException(Constant::INVALID_PARAMETER);
                            }
                            $czhima = D('Customer')->saveCustomerzhima($consume['customer_id']);
                            if (!$czhima){
                                BusinessException::throwException(Constant::INVALID_PARAMETER);
                            }
                        }
                    }
                }
            } elseif ($resulte['status'] == 'PAY_FAIL'){
                Log::pay_write("订单号为：".$order_id."返回成功但是查询失败");
                $map = [];
                $map['id'] = $resultstatu['order_no'];
                $data =[];
                $data['repay'] = 0;
                M('consume_history',null)->where($map)->setField($data);
                //付款提交失败
                $status = 3;
                $ret_msg2 ="提交付款失败";
                $ret_code2 = 1112;
                $ret_code = $ret_code?$ret_code:'1111';
                $ret_msg = $ret_msg?$ret_msg:'还款失败';
                $sqldata = array('ret_msg'=>$ret_msg,'ret_code'=>$ret_code,'status'=>$status);
                try{
                    $res = M('CustomerBillPayLog')->where(['order_id'=>$order_id])->save($sqldata);

                }catch (BusinessException $e){
                    Log::pay_write("划扣失败修改流水表".$e->getMessage());
                }
                Log::pay_write("划扣失败修改流水表".$customerId."orderid".$order_id."执行的语句".M('CustomerBillPayLog')->getLastSql()."执行结果".$res);
                //手动输入的预扣金额为零
                M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->setField(["final_amount"=>0]);
                Log::pay_write("交易中心划扣异步回调失败".$customerId."  交易中心划扣还款失败");
                $bank = $this->getDefaultCards($customerId);
                if (empty($bank)){
                    Log::pay_write("换卡请求交易中心划扣，但是此用户没有副卡，直接返回");
                } else{
                    $con = M('ConsumeHistory')->where(['id'=>$consume_id])->find();
                    $repay_date = $con['repayment_time'];
                    Log::pay_write("换卡请求交易中心划扣参数".$customerId."订单号".$consume_id."金额".$amount."最后还款时间".$repay_date."kind".$kind."typeof".$typeof);
                    $this->payConfirmParts($customerId,$consume_id,$amount,$repay_date,$kind,$typeof);
                }
            } else {
                Log::pay_write("此订单正在处理中".$order_id."用户".$customerId);
            }
        } elseif ($resultstatu['code'] == 400) {
            Log::pay_write("订单号为：".$order_id."不等于200，走else");
            $map = [];
            $map['id'] = $resultstatu['order_no'];
//            $cons = $resultstatu['order_no'];
            $data =[];
            $data['repay'] = 0;
            M('consume_history',null)->where($map)->setField($data);
//            $sql  = "update consume_history set repay = 0 where id = ".$cons;
//            $rescon = M()->query($sql);
//            Log::pay_write("返回结果为400修改订单表".$order_id."语句".$sql."结果".$rescon);
            //付款提交失败
            $status = 3;
            $ret_codes = $ret_code?$ret_code:'1111';
            $ret_msgs = $ret_msg?$ret_msg:'还款失败';
            $sqldata1 = array('ret_msg'=>$ret_msgs,'ret_code'=>$ret_codes,'status'=>$status);
            $ress = M('customer_bill_pay_log',null)->where(['order_id'=>$order_id])->save($sqldata1);
//            $sql1 = "update customer_bill_pay_log set ret_msg = '".$ret_msgs."' ret_code = ".$ret_codes." status = ".$status." where order_id = ".$order_id;
//            $rescusbill = M()->query($sql1);
//            Log::pay_write("划扣失败修改流水表".$customerId."orderid".$order_id."执行的语句".$sql1."执行结果".$rescusbill);
            Log::pay_write("划扣失败修改流水表".$customerId."orderid".$order_id."执行的语句".M('customer_bill_pay_log',null)->getLastSql()."执行结果".$ress);
            //手动输入的预扣金额为零
            M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->setField(["final_amount"=>0]);
            if ($ress === 0){
                Log::pay_write("划扣回调重试开始".$order_id);
                sleep(3);
                $map = [];
                $map['id'] = $resultstatu['order_no'];
                $data =[];
                $data['repay'] = 0;
                M('consume_history',null)->where($map)->setField($data);
                //付款提交失败
                $status = 3;
                $ret_codes = $ret_code?$ret_code:'1111';
                $ret_msgs = $ret_msg?$ret_msg:'还款失败';
                $sqldata1 = array('ret_msg'=>$ret_msgs,'ret_code'=>$ret_codes,'status'=>$status);
                $ressa = M('customer_bill_pay_log',null)->where(['order_id'=>$order_id])->save($sqldata1);
                Log::pay_write("划扣回调重试结果".$ressa."订单号".$order_id);
                M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->setField(["final_amount"=>0]);
            }
//            $sql2 = "update consume_installment_history set final_amount = 0 where parent_id = ".$consume_id;
//            $reshis = M()->query($sql2);
//            Log::pay_write("返回结果为400修改订单表".$order_id."语句".$sql."结果".$reshis);
            Log::pay_write("交易中心划扣异步回调失败".$customerId."  交易中心划扣还款失败");
            $bank = $this->getDefaultCards($customerId);
            if (empty($bank)){
                Log::pay_write("换卡请求交易中心划扣，但是此用户没有副卡，直接返回");
            } else{
                $con = M('ConsumeHistory')->where(['id'=>$consume_id])->find();
                $repay_date = $con['repayment_time'];
                Log::pay_write("换卡请求交易中心划扣参数".$customerId."订单号".$consume_id."金额".$amount."最后还款时间".$repay_date."kind".$kind."typeof".$typeof);
                $this->payConfirmParts($customerId,$consume_id,$amount,$repay_date,$kind,$typeof);
            }
        }
        echo "success";
    }

    public function pushOrderId(){
        set_time_limit(0);
        $sql = "select * from customer_bill_pay_log where ret_msg = '' and create_time > '2017-12-12 00:00:00' limit 5000";
        $resa = M()->query($sql);

//        echo "".$sql;
        foreach ($resa as $key => $val){

            $order_id = $val['order_id'];
            $url = "http://zqhfundtest.huoyanzichan.com/RepayMoney/Pay/testSearch?requestno=".$order_id;
            $resultes = file_get_contents($url);
//            echo $resultes;
            $resulte = json_decode($resultes,true);
            Log::pay_write("pushOrderId查询订单信息".json_encode($resulte)."order_id".$order_id);
            $arr = [];
            if ($resulte['status'] == 'PAY_SUCCESS'){
//                echo 'success';
                $arr['code'] = 200;
                $arr['result_cdoe'] = 0000;
                $arr['result_msg'] = 'success';
                $arr['amount'] = $resulte['amount'];
            } else if($resulte['status'] == 'PAY_FAIL') {
//                echo 'failed';
                $arr['code'] = 400;
                $arr['result_cdoe'] = 400;
                $arr['result_msg'] = $resulte['errormsg'];
            } else {
                Log::pay_write("需要做记录order_id".$order_id);
                continue;
            }
            $arr['trade_no'] = $order_id;
            $res = M('ZqhfundMqRepayment')->field('order_no,pay_type,res_pay,customer_id')->where(['trade_no'=>$order_id])->find();
            $arr['order_no'] = $res['order_no'];
            $arr['pay_type'] = $res['pay_type'];
            $arr['typeof'] = $res['res_pay'];
            $arr['customer_id'] = $res['customer_id'];
            Log::pay_write("pushOrderId请求数据".json_encode($arr)."order_id".$order_id."请求url".$url);
//            echo json_encode($arr);
            $this->huakouhuidiaos_($arr);

        }
    }
    public function pushOrderIdYinShengTest(){
        echo 'start-  ';
        Log::pay_write("pushOrderIdYinShengTest-------start");
        set_time_limit(0);
        $sql = "select * from customer_bill_pay_log where ret_msg = '' and create_time > '2017-11-07 00:00:00' limit 5000";
        $resa = M()->query($sql);
        echo '   sql语句'.$sql;
        Log::pay_write("pushOrderId查询订单信息--银生宝--".$sql);
        foreach ($resa as $key => $val){
            $order_id = $val['order_id'];
            $url = "http://testapiapi.huoyanzichan.com/RepayMoney/Pay/testSearchYinSheng?requestno=".$order_id;
            Log::pay_write("pushOrderId查询订单信息--银生宝".$url);
            $resultes = file_get_contents($url);
            echo '    返回结果'.$resultes;
            Log::pay_write("pushOrderId查询订单信息--银生宝".$resultes."order_id".$order_id);
            //echo $resultes;
            $resulte = json_decode($resultes,true);
            Log::pay_write("pushOrderId查询订单信息   银生宝".json_encode($resulte)."order_id".$order_id);
            $arr = [];
            if ($resulte['status'] == '00'){
                Log::pay_write("pushOrderId查询订单信息     成功的".json_encode($resulte)."order_id".$order_id);
                echo '   '.$order_id.'success';
                $arr['code'] = 200;
                $arr['result_cdoe'] = 0000;
                $arr['result_msg'] = 'success';
                $arr['amount'] = $resulte['amount'];
            } else if($resulte['status'] == '20') {
                Log::pay_write("pushOrderId查询订单信息    失败的".json_encode($resulte)."order_id".$order_id);
                echo '   '.$order_id.'failed';
                $arr['code'] = 400;
                $arr['result_cdoe'] = 400;
                $arr['result_msg'] = $resulte['desc']?$resulte['desc']:'余额不足';
            } else {
                echo '   '.$order_id.'其他情况'.json_encode($resulte);
                Log::pay_write("需要做记录   银生宝order_id".$order_id);
                continue;
            }
            $arr['trade_no'] = $order_id;
            $res = M('ZqhfundMqRepayment')->field('order_no,pay_type,res_pay,customer_id')->where(['trade_no'=>$order_id])->find();
            $arr['order_no'] = $res['order_no'];
            $arr['pay_type'] = $res['pay_type'];
            $arr['typeof'] = $res['res_pay'];
            $arr['customer_id'] = $res['customer_id'];
            Log::pay_write("pushOrderId请求数据".json_encode($arr)."order_id".$order_id."请求url".$url);
            echo '     最终请求'.json_encode($arr);
            $this->huakouhuidiaos_($arr);

        }

    }

    public function  huakouhuidiaos_($arr){
        $resultstatu=$arr;
        Log::pay_write("huakouhuidiaos用户还款交易中心回调接收数据     ".json_encode($resultstatu));
        $CustomerBillPayLog = M('CustomerBillPayLog');
        $ret_code = $resultstatu['result_code'];
        $ret_msg = $resultstatu['result_msg'];
        $order_id = $resultstatu['trade_no'];
        $amount = $resultstatu['amount']*100;
        $customerId = $resultstatu['customer_id'];
        $consume_id = $resultstatu['order_no'];
        $kind = $resultstatu['pay_type'];
        $typeof = $resultstatu['typeof'] == ''?0:$resultstatu['typeof'];
        $panduanmsg = $CustomerBillPayLog->field('ret_msg')->where(['order_id'=>$order_id])->find();
        if (!empty($panduanmsg['ret_msg'])){
            Log::pay_write("此订单号".$order_id."已经处理了，这块不做处理直接返回");
            return;
        }
        if($resultstatu['code'] == 200){
            Log::pay_write('*huakouhuidiaos_查询用户'.$order_id.'是否实际还款返回结果status：200     huakouhuidiaos划扣成功');
            //还款成功写库
            $ret_code = $ret_code?$ret_code:'0000';
            $sqldata = array('ret_msg'=>'success','pay_time'=>time(),'ret_code'=>$ret_code,'status'=>1);
            Log::pay_write('huakouhuidiaos查询用户'.$order_id.'是否实际还款返回结果status：200|成功'.json_encode($sqldata));
            $CustomerBillPayLog->where(['order_id'=>$order_id,'status'=>0])->setField($sqldata);
//            $ret = Constant::getReturn(Constant::SUCCESS);
//            $ret['data'] = array('order_id'=>$order_id,'trade_no'=>$order_id,'amount' => $amount,'pay_action' => $pay_action,'customer_id' => $customerId,'pay_time' => date('Y-m-d H:i:s',time()));
            if ($kind == '3'){
                Log::pay_write("huakouhuidiaos-用户部分还款开始  ".$customerId."    回调数据   ".json_encode($resultstatu));
                M('ConsumeHistory')->where(['id'=>$consume_id,'type'=>5,'status'=>1])->setField(['typeof'=>$typeof]);
                $res = M('ConsumeHistory')->field('part_need_pay_amount,part_pay_amount,consume_amount,repayment_time,update_time')->where(['id'=>$consume_id,'type'=>5,'status'=>1])->find();
                $part_pay_amount = $amount + $res['part_pay_amount'];
                $data1 = date("Y-m-d H:i:s", time());
                $data4 = date("Y-m-d", time());
                $data2 = date("Y-m-d H:i:s", $res['repayment_time']);
                $data3 = date("Y-m-d", $res['update_time']);
                $date = floor((strtotime($data1) - strtotime($data2)) / 86400);
                $date1 = (strtotime($data4) - strtotime($data3)) / 86400;
                if ($part_pay_amount < $res['consume_amount']){
                    if ($res['update_time'] == 0) {
                        $num = ($res['consume_amount'] - $res['part_pay_amount']) * Constant::Overdue_Interest_Rate * $date;
                        if (($num + Constant::OVER_DATE_RATE) > $res['consume_amount']){
                            $num = $res['consume_amount'] - Constant::OVER_DATE_RATE;
                        }
                        $part_need_pay_amount = $num + $res['consume_amount'] - $amount;
                    } else {
                        $num = ($res['consume_amount'] - $res['part_pay_amount']) * Constant::Overdue_Interest_Rate * $date1 + $res['part_need_pay_amount'];
                        $yihuan = $res['part_pay_amount'];
                        if (($num + $yihuan + Constant::OVER_DATE_RATE) > $res['consume_amount'] * 2){
                            $num = ($res['consume_amount'] * 2) - $yihuan - Constant::OVER_DATE_RATE;
                        }
                        $part_need_pay_amount = $num - $amount;
                    }
                    Log::pay_write('划扣--本金未还完   '.$customerId.'剩余还款金额 '.$part_need_pay_amount);
                } else {
                    if ($res['part_need_pay_amount'] == 0){
                        $num = ($res['consume_amount'] - $res['part_pay_amount']) * Constant::Overdue_Interest_Rate * $date;
                        if (($num + Constant::OVER_DATE_RATE) > $res['consume_amount']){
                            $num = $res['consume_amount'] - Constant::OVER_DATE_RATE;
                        }
                        $part_need_pay_amount = $num + $res['consume_amount'] - $amount;
                    } else {
                        $part_need_pay_amount = $res['part_need_pay_amount'] - $amount;
                    }
                    Log::pay_write('划扣--本金已还完   '.$customerId.'剩余还款金额 '.$part_need_pay_amount);
                }
                Log::pay_write("huakouhuidiaos".$customerId."最后数据   ".$part_need_pay_amount);
                if ($part_need_pay_amount < 0){
                    $part_need_pay_amount = 0;
//                    $part_pay_amount = $part_pay_amount + Constant::OVER_DATE_RATE;
                }
                Log::pay_write("huakouhuidiaos".$customerId."最后数据".$part_need_pay_amount."   填写金额   ".$part_pay_amount);
                M('ConsumeHistory')->where(['id'=>$consume_id,'type'=>5,'status'=>1])->setField(['part_need_pay_amount'=>$part_need_pay_amount,'part_pay_amount'=>$part_pay_amount,'update_time'=>time(),'repay'=>0]);
                if ($part_need_pay_amount == 0){
                    Log::pay_write("huakouhuidiaos".$customerId."  该用户（多次部分还款）贷款已结清");
                    $mobiles = M('Customer')->field('mobile,real_name')->where(['id'=>$customerId])->find();
                    if (!empty($mobiles)){
                        $res = M('ConsumeHistory')->field('consume_amount,add_time')->where(['id'=>$consume_id,'type'=>5,'status'=>1])->find();
                        $mobile = $mobiles['mobile'];
                        /*云峰开始|使用请直接打开注释|并注释掉上边的发送代码*/
                        $name = $mobiles['real_name'];
                        $part_pay_amount = $part_pay_amount/100;
                        $amounts = $res['consume_amount']/100;
                        $time = $res['add_time'];
                        $dates = date("Y年m月d日",$time);
                        Log::pay_write("amount".$amounts."时间".$time."最后时间".$dates."sql".M('ConsumeHistory')->getLastSql());
//                        $content = "【找钱花】尊敬的找钱花客户".$name."您好，您于".$dates."的".$amounts."元金额借款，现已成功还款".$part_pay_amount."元。剩余未还金额请尽快还款，以避免产生不必要的逾期费用，若已结清请忽略。感谢您的理解和支持！";
//                        $content = "【找钱花】尊敬的".$name."您好，您于".$dates."的".$amounts."借款，现还款".$part_pay_amount."元。未还清部分请尽快还款，避免产生不必要的逾期费用，若已结清请忽略。";
                        $content = "【找钱花】尊敬的".$name."您好，您于".$dates."的".$amounts."借款，现还款".$part_pay_amount."元。未还清部分请尽快还款，若已结清请忽略。";
                        $ret = SendSMS::yunfeng_send_json($mobile,$content);
                        Log::borrow_write("huakouhuidiaos+++++++++新版部分自动划扣短信---手机号:".$mobile."发短信结果".json_encode($ret).$content);
                    }
                    Log::pay_write("用户部分还款".$customerId."全部还清++++修改状态5-1=>5-3");
                    Log::pay_write("这里是用于统计每次      全部还清划扣成功      用户".$customerId."本次还款".$amount."总共还款".$part_pay_amount);
                    M('ConsumeHistory')->where(['id'=>$consume_id,'type'=>5,'status'=>1])->setField(['status'=>3,'update_time'=>time(),'repay'=>0]);
                    M('Customer')->where(['id'=>$customerId])->setField(['balance_cash_amount'=>200000,'cash_amount'=>0]);
                    M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->setField(['status'=>1,'update_time'=>time(),"final_amount"=>0]);
                    $ConsumeUserInfo = M('ConsumeUser')->where("consume_id = $consume_id and status = 1")->find();
                    if (isset($ConsumeUserInfo) && !empty($ConsumeUserInfo)) {
                        $ConsumeUserStatusInfo = M('ConsumeUser')->where("consume_id = $consume_id and status = 1")->setField(array('status'=>2));
                    }
                    $consume = M('ConsumeHistory')->where(['id'=>$consume_id])->find();
                    if ($consume['status'] == 3){
                        $paylog = $CustomerBillPayLog->where(['order_id'=>$order_id])->find();
                        $consumehistory = M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->find();
                        if ($paylog['amount'] != $consumehistory['amount']){
                            $scredit = D('CustomerAuth')->saveCustomerAuth($consume['customer_id']);
                            if (!$scredit){
//                                BusinessException::throwException(Constant::INVALID_PARAMETER);
                                return;
                            }
                            $czhima = D('Customer')->saveCustomerzhima($consume['customer_id']);
                            if (!$czhima){
//                                BusinessException::throwException(Constant::INVALID_PARAMETER);
                                return;
                            }
                        }
                    }
                } else {
                    Log::pay_write("huakouhuidiaos".$customerId."  该用户贷款部分结清".'已还金额'.$part_pay_amount);
                    $mobiles = M('Customer')->field('mobile,real_name')->where(['id'=>$customerId])->find();
                    Log::pay_write("这里是用于统计每次     部分还清划扣成功     用户".$customerId."本次还款".$amount."总共还款".$part_pay_amount."剩余未还金额".$part_need_pay_amount);
                    if (!empty($mobiles)){
                        $mobile = $mobiles['mobile'];
                        $res = M('ConsumeHistory')->field('consume_amount,add_time,part_need_pay_amount,repayment_time')->where(['id'=>$consume_id,'type'=>5,'status'=>1])->find();
                        /*云峰开始|使用请直接打开注释|并注释掉上边的发送代码*/
                        $name = $mobiles['real_name'];
                        $part_pay_amount = $part_pay_amount/100;
                        $amounts = $res['consume_amount']/100;
                        $time = $res['add_time'];
                        $dates = date("Y年m月d日",$time);
                        Log::pay_write("amount".$amounts."时间".$time."最后时间".$dates."sql".M('ConsumeHistory')->getLastSql());
//                        $content = "【找钱花】尊敬的找钱花客户".$name."您好，您于".$dates."的".$amounts."元金额借款，现已成功还款".$part_pay_amount."元。剩余未还金额请尽快还款，以避免产生不必要的逾期费用。感谢您的理解和支持！";
//                        $content = "【找钱花】尊敬的".$name."您好，您于".$dates."的".$amounts."借款，现还款".$part_pay_amount."元。未还清部分请尽快还款，避免产生不必要的逾期费用。";
                        $content = "【找钱花】尊敬的".$name."您好，您于".$dates."的".$amounts."借款，现还款".$part_pay_amount."元。未还清部分请尽快还款，若已结清请忽略。";
                        $ret = SendSMS::yunfeng_send_json($mobile,$content);
                        Log::borrow_write("huakouhuidiaos+++++++++新版部分自动划扣短信---手机号:".$mobile."发短信结果".json_encode($ret).$content);
                    }
                    if ($res['part_need_pay_amount'] > $amount){
                        Log::borrow_write("huakouhuidiaos+++++++++新版部分自动划扣短信---手机号:".$mobile."发短信结果".json_encode($ret).$content);
                        //$customer_id,          $amount,          $repay_date,          $kind,          $typeof
                        $repay_date = $res['repayment_time'];
                        $num = $res['part_need_pay_amount'] + Constant::OVER_DATE_RATE - $amount;
                        if ($num < 10000){
                            $am = $res['part_need_pay_amount'] + Constant::OVER_DATE_RATE;
                        } else {
                            $am = $amount;
                        }
                    } else {
                        Log::borrow_write("huakouhuidiaos+++++++++新版部分自动划扣短信---手机号:".$mobile."发短信结果".json_encode($ret).$content);
                        $repay_date = $res['repayment_time'];
                        $am = $res['part_need_pay_amount'] + Constant::OVER_DATE_RATE;
                    }
                    Log::pay_write("循环划扣    再次请求参数".$customerId."++++".$am."++++".$repay_date."++++".$kind."++++".$typeof);
                    $this->payConfirmPart($customerId,$consume_id,$am,$repay_date,$kind,$typeof);
                }
            } else {
                Log::pay_write("huakouhuidiaos".$customerId."   该用户还全款成功");
                $res = M('ConsumeHistory')->field('part_pay_amount,repayment_time')->where(['id'=>$consume_id,'type'=>5,'status'=>1])->find();
                $part_pay_amount = $amount + $res['part_pay_amount'];
                //更新订单状态到已还款完成
                M('ConsumeHistory')->where(['id'=>$consume_id,'type'=>5,'status'=>1])->setField(['status'=>3,'update_time'=>time(),'part_pay_amount'=>$part_pay_amount,'part_need_pay_amount'=>0,'repay'=>0]);
                M('Customer')->where(['id'=>$customerId])->setField(['balance_cash_amount'=>200000,'cash_amount'=>0]);
                M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->setField(['status'=>1,'update_time'=>time(),"final_amount"=>0]);
                $mobiles = M('Customer')->field('mobile')->where(['id'=>$customerId])->find();
                if (!empty($mobiles)){
                    $mobile = $mobiles['mobile'];
                    $timecha = $res['repayment_time'];
                    $day1=strtotime(date("Y-m-d 23:59:59",time()))-86400;//逾期一天
                    $day2=strtotime(date("Y-m-d 23:59:59",time()))-2592000;//逾期三十天
                    if ($timecha >= $day2 && $timecha <= $day1){
                        $content = "【找钱花】尊敬的找钱花客户，您的逾期借款已经划扣成功，祝您生活愉快";
                    } else {
                        $content = "【找钱花】尊敬的找钱花客户，您的还款系统划扣已成功，祝您生活愉快";
                    }
                    $ret = SendSMS::yunfeng_send_json($mobile,$content);
                    Log::borrow_write("++huakouhuidiaos+++++++新版自动划扣短信---手机号:".$mobile."发短信结果".json_encode($ret), Log::DEBUG);
                }
                Log::pay_write("这里是用于统计每次      一次还清划扣成功      用户".$customerId."本次还款".$amount."总共还款".$part_pay_amount);
                /****这里扣款成功修改status给贷后分单用，防止撤单分单出现已还款仍能撤分单***/
                $ConsumeUserInfo = M('ConsumeUser')->where("consume_id = $consume_id and status = 1")->find();
                if (isset($ConsumeUserInfo) && !empty($ConsumeUserInfo)) {
                    $ConsumeUserStatusInfo = M('ConsumeUser')->where("consume_id = $consume_id and status = 1")->setField(array('status'=>2));
                }
                $consume = M('ConsumeHistory')->where(['id'=>$consume_id])->find();
                if ($consume['status'] == 3){
                    $paylog = $CustomerBillPayLog->where(['order_id'=>$order_id])->find();
                    $consumehistory = M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->find();
                    if ($paylog['amount'] != $consumehistory['amount']){
                        $scredit = D('CustomerAuth')->saveCustomerAuth($consume['customer_id']);
                        if (!$scredit){
//                            BusinessException::throwException(Constant::INVALID_PARAMETER);
                            return;
                        }
                        $czhima = D('Customer')->saveCustomerzhima($consume['customer_id']);
                        if (!$czhima){
//                            BusinessException::throwException(Constant::INVALID_PARAMETER);
                            return;
                        }
                    }
                }
            }
        } else {
            $map = [];
            $map['id'] = $resultstatu['order_no'];
            $data =[];
            $data['repay'] = 0;
            M('consume_history',null)->where($map)->setField($data);
            //付款提交失败
            $status = 3;
            $ret_msg2 ="提交付款失败";
            $ret_code2 = 1112;
            $ret_code = $ret_code?$ret_code:'1111';
            $ret_msg = $ret_msg?$ret_msg:'还款失败';
            $sqldata = array('ret_msg'=>$ret_msg,'ret_code'=>$ret_code,'status'=>$status);
            $CustomerBillPayLog->where(['order_id'=>$order_id,'status'=>0])->setField($sqldata);
            //手动输入的预扣金额为零
            M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id,'update_time'=>0])->setField(["final_amount"=>0]);
            Log::pay_write("交易中心划扣异步回调失败".$customerId."  交易中心划扣还款失败");
        }
    }

    //换卡请求交易中心划扣跳转
    public function payConfirmParts($customer_id,$consume_id,$amount,$repay_date,$kind,$typeof){
        Log::pay_write("换卡请求交易中心划扣接收参数".$customer_id."订单号".$consume_id."金额".$amount."最后还款时间".$repay_date."kind".$kind."typeof".$typeof);
        $bank = $this->getDefaultCards($customer_id);
        if (empty($bank)){
            Log::pay_write("换卡请求交易中心划扣，但是此用户没有副卡，直接返回");
            return;
        } else {
            $customer = M('Customer')->field('id_num')->where(['id'=>$customer_id])->find();
            $consume = M('ConsumeHistory')->where(['id'=>$consume_id])->select();
            Log::pay_write("payConfirmPart--用户ID".$customer_id."********订单信息".json_encode($consume)."**********用户信息".json_encode($customer));
            if ($consume[0]['type'] == 5 && $consume[0]['status'] == 1 && $consume[0]['repay'] == 0){
                $url = "http://zqhfundtest.huoyanzichan.com/RepayMoney/Pay/consumePayRequest";
                $data = [];
                $data['sub_contract_id'] = $bank['sub_contract_id'];
                $data['real_name'] = $bank['card_user_name'];
                $data['card_num'] = $bank['card_num'];
                $data['reser_phone'] = $bank['reserved_mobile'];
                $data['id_card_no'] = $customer['id_num'];
                if ($bank['gate_id'] == 'ABC'){
                    $data['source'] = 1;
                } else {
                    $data['source'] = 2;
                }
//            $data['source'] = $bank['source']?$bank['source']:1;
                $data['type'] = 1;
                $data['customer_id'] = $customer_id;
                $data['consume_id'] = $consume_id;
                $data['amount'] = $amount/100;
                $data['callback_url'] = "http://api1.huoyanzichan.com/Home/Pay/huakouhuidiaoss";
                $data['trade_no'] = $this->trade_no();
                $data['pay_type'] = $kind;
                $data['typeof'] = $typeof?$typeof:0;
                $CustomerBillPayLog = M('CustomerBillPayLog');
                Log::pay_write("脚本划扣参数".json_encode($data)."用户".$customer_id);
                $ress = D('Ajax')->ajaxPosts($url,$data);
                $res = json_decode($ress,true);
                Log::pay_write("payConfirmPart交易中心".$data['consume_id']."返回结果     ".$res['code']."    ".json_encode($res));
                if ($res['code'] == 200){
                    $sqldata = ['repay'=>1];
                    M('ConsumeHistory')->where(['id'=>$data['consume_id']])->save($sqldata);
                    Log::pay_write("payConfirmPart  交易中心".$data['consume_id']."接受请求返回结果成功 ".json_encode($res));
                    //入库
                    $datass = array(
                        'order_id' => $data['trade_no'],
                        'order_type' => 1,
                        'customer_id' => $customer_id,
                        'consume_id' => $consume_id,
                        'consume_data' => json_encode($data),
                        'repay_date' => date("Y-m-d",$repay_date),
                        'amount' => $amount,
                        'trade_id' => '',
                        'pay_type' => 1,
                        'type' => 1,
                        'balance_amount_old' =>'',
                        'balance_cash_amount_old' =>'',
                        'overdue_amount' => '',
                        'pay_action' => 2,
                    );
                    if (false === ($insertId = $CustomerBillPayLog->add($datass))) {
                        BusinessException::throwException('支付订单创建失败');
                    }
                    $rea = ['code'=>200];
                    echo json_encode($rea);return;
                } else {
                    Log::pay_write("payConfirmPart 交易中心".$data['consume_id']."接受请求返回结果失败   orderid ".$data['consume_id']."+++++++".json_encode($res));
                    $rea = ['code'=>400];
                    echo json_encode($rea);return;
                }
            } else {
                Log::pay_write("payConfirmPart 此订单不能划扣".$consume_id);
                return false;
            }
        }

    }
    //换卡交易中心划扣异步回调
    public function huakouhuidiaoss(){
        Log::pay_write("这就是为了统计换卡划扣数量的");
        $resultstatu = file_get_contents('php://input');
        $resultstatu = json_decode($resultstatu,true);
        Log::pay_write("huakouhuidiaoss用户换卡还款交易中心回调接收数据     ".json_encode($resultstatu));
        $CustomerBillPayLog = M('CustomerBillPayLog');
        $ret_code = $resultstatu['result_code'];
        $ret_msg = $resultstatu['result_msg'];
        $trade_state = $resultstatu['trade_state'];
        $order_id = $resultstatu['trade_no'];
        $amount = $resultstatu['amount']*100;
        $customerId = $resultstatu['customer_id'];
        $consume_id = $resultstatu['order_no'];
        $kind = $resultstatu['pay_type'];
        $typeof = $resultstatu['typeof'] == ''?0:$resultstatu['typeof'];
        $panduanmsg = $CustomerBillPayLog->field('ret_msg')->where(['order_id'=>$order_id])->find();
        if (!empty($panduanmsg['ret_msg'])){
            Log::pay_write("此订单号".$order_id."已经处理了，这块不做处理直接返回");
            return;
        }
        if($resultstatu['code'] == 200){
            Log::pay_write('*huakouhuidiaoss查询用户'.$order_id.'是否实际换卡还款返回结果status：200     huakouhuidiaos划扣成功');
            //还款成功写库
            $ret_code = $ret_code?$ret_code:'0000';
            $sqldata = array('ret_msg'=>'success','pay_time'=>time(),'ret_code'=>$ret_code,'status'=>1);
            Log::pay_write('huakouhuidiaoss查询用户'.$order_id.'是否实际换卡还款返回结果status：200|成功'.json_encode($sqldata));
            $CustomerBillPayLog->where(['order_id'=>$order_id,'status'=>0])->setField($sqldata);
//            $ret = Constant::getReturn(Constant::SUCCESS);
//            $ret['data'] = array('order_id'=>$order_id,'trade_no'=>$order_id,'amount' => $amount,'pay_action' => $pay_action,'customer_id' => $customerId,'pay_time' => date('Y-m-d H:i:s',time()));
            if ($kind == '3'){
                Log::pay_write("huakouhuidiaos-用户部分换卡还款开始  ".$customerId."    回调数据   ".json_encode($resultstatu));
                M('ConsumeHistory')->where(['id'=>$consume_id,'type'=>5,'status'=>1])->setField(['typeof'=>$typeof]);
                $res = M('ConsumeHistory')->field('part_need_pay_amount,part_pay_amount,consume_amount,repayment_time,update_time')->where(['id'=>$consume_id,'type'=>5,'status'=>1])->find();
                $part_pay_amount = $amount + $res['part_pay_amount'];
                $data1 = date("Y-m-d H:i:s", time());
                $data4 = date("Y-m-d", time());
                $data2 = date("Y-m-d H:i:s", $res['repayment_time']);
                $data3 = date("Y-m-d", $res['update_time']);
                $date = floor((strtotime($data1) - strtotime($data2)) / 86400);
                $date1 = (strtotime($data4) - strtotime($data3)) / 86400;
                if ($part_pay_amount < $res['consume_amount']){
                    if ($res['update_time'] == 0) {
                        $num = ($res['consume_amount'] - $res['part_pay_amount']) * Constant::Overdue_Interest_Rate * $date;
                        if (($num + Constant::OVER_DATE_RATE) > $res['consume_amount']){
                            $num = $res['consume_amount'] - Constant::OVER_DATE_RATE;
                        }
                        $part_need_pay_amount = $num + $res['consume_amount'] - $amount;
                    } else {
                        $num = ($res['consume_amount'] - $res['part_pay_amount']) * Constant::Overdue_Interest_Rate * $date1 + $res['part_need_pay_amount'];
                        $yihuan = $res['part_pay_amount'];
                        if (($num + $yihuan + Constant::OVER_DATE_RATE) > $res['consume_amount'] * 2){
                            $num = ($res['consume_amount'] * 2) - $yihuan - Constant::OVER_DATE_RATE;
                        }
                        $part_need_pay_amount = $num - $amount;
                    }
                    Log::pay_write('划扣--本金未还完   '.$customerId.'剩余还款金额 '.$part_need_pay_amount);
                } else {
                    if ($res['part_need_pay_amount'] == 0){
                        $num = ($res['consume_amount'] - $res['part_pay_amount']) * Constant::Overdue_Interest_Rate * $date;
                        if (($num + Constant::OVER_DATE_RATE) > $res['consume_amount']){
                            $num = $res['consume_amount'] - Constant::OVER_DATE_RATE;
                        }
                        $part_need_pay_amount = $num + $res['consume_amount'] - $amount;
                    } else {
                        $part_need_pay_amount = $res['part_need_pay_amount'] - $amount;
                    }
                    Log::pay_write('划扣--本金已还完   '.$customerId.'剩余还款金额 '.$part_need_pay_amount);
                }
                Log::pay_write("huakouhuidiaos".$customerId."最后数据   ".$part_need_pay_amount);
                if ($part_need_pay_amount < 0){
                    $part_need_pay_amount = 0;
//                    $part_pay_amount = $part_pay_amount + Constant::OVER_DATE_RATE;
                }
                Log::pay_write("huakouhuidiaos".$customerId."最后数据".$part_need_pay_amount."   填写金额   ".$part_pay_amount);
                M('ConsumeHistory')->where(['id'=>$consume_id,'type'=>5,'status'=>1])->setField(['part_need_pay_amount'=>$part_need_pay_amount,'part_pay_amount'=>$part_pay_amount,'update_time'=>time(),'repay'=>0]);
                if ($part_need_pay_amount == 0){
                    Log::pay_write("huakouhuidiaos".$customerId."  该用户（多次部分还款）贷款已结清");
                    $mobiles = M('Customer')->field('mobile,real_name')->where(['id'=>$customerId])->find();
                    if (!empty($mobiles)){
                        $res = M('ConsumeHistory')->field('consume_amount,add_time')->where(['id'=>$consume_id,'type'=>5,'status'=>1])->find();
                        $mobile = $mobiles['mobile'];
                        /*云峰开始|使用请直接打开注释|并注释掉上边的发送代码*/
                        $name = $mobiles['real_name'];
                        $part_pay_amount = $part_pay_amount/100;
                        $amounts = $res['consume_amount']/100;
                        $time = $res['add_time'];
                        $dates = date("Y年m月d日",$time);
                        Log::pay_write("amount".$amounts."时间".$time."最后时间".$dates."sql".M('ConsumeHistory')->getLastSql());
//                        $content = "【找钱花】尊敬的找钱花客户".$name."您好，您于".$dates."的".$amounts."元金额借款，现已成功还款".$part_pay_amount."元。剩余未还金额请尽快还款，以避免产生不必要的逾期费用，若已结清请忽略。感谢您的理解和支持！";
//                        $content = "【找钱花】尊敬的".$name."您好，您于".$dates."的".$amounts."借款，现还款".$part_pay_amount."元。未还清部分请尽快还款，避免产生不必要的逾期费用，若已结清请忽略。";
                        $content = "【找钱花】尊敬的".$name."您好，您于".$dates."的".$amounts."借款，现还款".$part_pay_amount."元。未还清部分请尽快还款，若已结清请忽略。";
                        $ret = SendSMS::yunfeng_send_json($mobile,$content);
                        Log::borrow_write("huakouhuidiaos+++++++++新版部分自动换卡划扣短信---手机号:".$mobile."发短信结果".json_encode($ret).$content);
                    }
                    Log::pay_write("用户部分还款".$customerId."全部还清++++修改状态5-1=>5-3");
                    Log::pay_write("这里是用于统计每次换卡      全部还清划扣成功      用户".$customerId."本次还款".$amount."总共还款".$part_pay_amount);
                    M('ConsumeHistory')->where(['id'=>$consume_id,'type'=>5,'status'=>1])->setField(['status'=>3,'update_time'=>time(),'repay'=>0]);
                    M('Customer')->where(['id'=>$customerId])->setField(['balance_cash_amount'=>200000,'cash_amount'=>0]);
                    M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->setField(['status'=>1,'update_time'=>time(),"final_amount"=>0]);
                    $ConsumeUserInfo = M('ConsumeUser')->where("consume_id = $consume_id and status = 1")->find();
                    if (isset($ConsumeUserInfo) && !empty($ConsumeUserInfo)) {
                        $ConsumeUserStatusInfo = M('ConsumeUser')->where("consume_id = $consume_id and status = 1")->setField(array('status'=>2));
                    }
                    $consume = M('ConsumeHistory')->where(['id'=>$consume_id])->find();
                    if ($consume['status'] == 3){
                        $paylog = $CustomerBillPayLog->where(['order_id'=>$order_id])->find();
                        $consumehistory = M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->find();
                        if ($paylog['amount'] != $consumehistory['amount']){
                            $scredit = D('CustomerAuth')->saveCustomerAuth($consume['customer_id']);
                            if (!$scredit){
                                BusinessException::throwException(Constant::INVALID_PARAMETER);
                            }
                            $czhima = D('Customer')->saveCustomerzhima($consume['customer_id']);
                            if (!$czhima){
                                BusinessException::throwException(Constant::INVALID_PARAMETER);
                            }
                        }
                    }
                } else {
                    Log::pay_write("huakouhuidiaos".$customerId."  该用户贷款部分结清".'已还金额'.$part_pay_amount);
                    $mobiles = M('Customer')->field('mobile,real_name')->where(['id'=>$customerId])->find();
                    Log::pay_write("这里是用于统计每次换卡     部分还清划扣成功     用户".$customerId."本次还款".$amount."总共还款".$part_pay_amount."剩余未还金额".$part_need_pay_amount);
                    if (!empty($mobiles)){
                        $mobile = $mobiles['mobile'];
                        $res = M('ConsumeHistory')->field('consume_amount,add_time,part_need_pay_amount,repayment_time')->where(['id'=>$consume_id,'type'=>5,'status'=>1])->find();
                        /*云峰开始|使用请直接打开注释|并注释掉上边的发送代码*/
                        $name = $mobiles['real_name'];
                        $part_pay_amount = $part_pay_amount/100;
                        $amounts = $res['consume_amount']/100;
                        $time = $res['add_time'];
                        $dates = date("Y年m月d日",$time);
                        Log::pay_write("amount".$amounts."时间".$time."最后时间".$dates."sql".M('ConsumeHistory')->getLastSql());
//                        $content = "【找钱花】尊敬的找钱花客户".$name."您好，您于".$dates."的".$amounts."元金额借款，现已成功还款".$part_pay_amount."元。剩余未还金额请尽快还款，以避免产生不必要的逾期费用。感谢您的理解和支持！";
//                        $content = "【找钱花】尊敬的".$name."您好，您于".$dates."的".$amounts."借款，现还款".$part_pay_amount."元。未还清部分请尽快还款，避免产生不必要的逾期费用。";
                        $content = "【找钱花】尊敬的".$name."您好，您于".$dates."的".$amounts."借款，现还款".$part_pay_amount."元。未还清部分请尽快还款，若已结清请忽略。";
                        $ret = SendSMS::yunfeng_send_json($mobile,$content);
                        Log::borrow_write("huakouhuidiaos+++++++++新版部分自动换卡划扣短信---手机号:".$mobile."发短信结果".json_encode($ret).$content);
                    }
                    if ($res['part_need_pay_amount'] > $amount){
                        //$customer_id,          $amount,          $repay_date,          $kind,          $typeof
                        $repay_date = $res['repayment_time'];
                        $num = $res['part_need_pay_amount'] + Constant::OVER_DATE_RATE - $amount;
                        if ($num < 10000){
                            $am = $res['part_need_pay_amount'] + Constant::OVER_DATE_RATE;
                        } else {
                            $am = $amount;
                        }
                    } else {
                        $repay_date = $res['repayment_time'];
                        $am = $res['part_need_pay_amount'] + Constant::OVER_DATE_RATE;
                    }
                    Log::pay_write("循环划扣换卡    再次请求参数".$customerId."++++".$am."++++".$repay_date."++++".$kind."++++".$typeof);
                    $this->payConfirmParts($customerId,$consume_id,$am,$repay_date,$kind,$typeof);
                }
            } else {
                Log::pay_write("huakouhuidiaos".$customerId."   该用户还全款成功");
                $res = M('ConsumeHistory')->field('part_pay_amount,repayment_time')->where(['id'=>$consume_id,'type'=>5,'status'=>1])->find();
                $part_pay_amount = $amount + $res['part_pay_amount'];
                //更新订单状态到已还款完成
                M('ConsumeHistory')->where(['id'=>$consume_id,'type'=>5,'status'=>1])->setField(['status'=>3,'update_time'=>time(),'part_pay_amount'=>$part_pay_amount,'part_need_pay_amount'=>0,'repay'=>0]);
                M('Customer')->where(['id'=>$customerId])->setField(['balance_cash_amount'=>200000,'cash_amount'=>0]);
                M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->setField(['status'=>1,'update_time'=>time(),"final_amount"=>0]);
                $mobiles = M('Customer')->field('mobile')->where(['id'=>$customerId])->find();
                if (!empty($mobiles)){
                    $mobile = $mobiles['mobile'];
                    $timecha = $res['repayment_time'];
                    $day1=strtotime(date("Y-m-d 23:59:59",time()))-86400;//逾期一天
                    $day2=strtotime(date("Y-m-d 23:59:59",time()))-2592000;//逾期三十天
                    if ($timecha >= $day2 && $timecha <= $day1){
                        $content = "【找钱花】尊敬的找钱花客户，您的逾期借款已经划扣成功，祝您生活愉快";
                    } else {
                        $content = "【找钱花】尊敬的找钱花客户，您的还款系统划扣已成功，祝您生活愉快";
                    }
                    $ret = SendSMS::yunfeng_send_json($mobile,$content);
                    Log::borrow_write("++huakouhuidiaos+++++++新版自动划扣短信---手机号:".$mobile."发短信结果".json_encode($ret), Log::DEBUG);
                }
                Log::pay_write("这里是用于统计每次      一次还清划扣成功      用户".$customerId."本次还款".$amount."总共还款".$part_pay_amount);
                /****这里扣款成功修改status给贷后分单用，防止撤单分单出现已还款仍能撤分单***/
                $ConsumeUserInfo = M('ConsumeUser')->where("consume_id = $consume_id and status = 1")->find();
                if (isset($ConsumeUserInfo) && !empty($ConsumeUserInfo)) {
                    $ConsumeUserStatusInfo = M('ConsumeUser')->where("consume_id = $consume_id and status = 1")->setField(array('status'=>2));
                }
                $consume = M('ConsumeHistory')->where(['id'=>$consume_id])->find();
                if ($consume['status'] == 3){
                    $paylog = $CustomerBillPayLog->where(['order_id'=>$order_id])->find();
                    $consumehistory = M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->find();
                    if ($paylog['amount'] != $consumehistory['amount']){
                        $scredit = D('CustomerAuth')->saveCustomerAuth($consume['customer_id']);
                        if (!$scredit){
                            BusinessException::throwException(Constant::INVALID_PARAMETER);
                        }
                        $czhima = D('Customer')->saveCustomerzhima($consume['customer_id']);
                        if (!$czhima){
                            BusinessException::throwException(Constant::INVALID_PARAMETER);
                        }
                    }
                }
            }
        } else {
            $map = [];
            $map['id'] = $resultstatu['order_no'];
            $data =[];
            $data['repay'] = 0;
            M('consume_history',null)->where($map)->setField($data);
            //付款提交失败
            $status = 3;
            $ret_msg2 ="提交付款失败";
            $ret_code2 = 1112;
            $ret_code = $ret_code?$ret_code:'1111';
            $ret_msg = $ret_msg?$ret_msg:'还款失败';
            $sqldata = array('ret_msg'=>$ret_msg,'ret_code'=>$ret_code,'status'=>$status);
            $CustomerBillPayLog->where(['order_id'=>$order_id,'status'=>0])->setField($sqldata);
            //手动输入的预扣金额为零
            M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->setField(["final_amount"=>0]);
            Log::pay_write("交易中心划扣异步回调失败".$customerId."  交易中心划扣还款失败");
        }
        echo "success";
    }
    //新版获取银行卡（副卡）
    public  function  getDefaultCards($customer_id){
        //新的表
        $map = [];
        $map['customer_id'] = $customer_id;
        $map['is_default'] = 0;
        $newlists = M('customer_bank_info_new',null)
            ->field('customer_id,card_user_name,sub_contract_id,
                    card_num,reserved_mobile,usr_busi_agreement_id,
                    usr_pay_agreement_id,gate_id,bank_card_type,
                    is_default,source,bank_address')
            ->where($map)
            ->find();
        if($newlists){//new  table  has user data
            return $newlists;
        }else{//new table  does not have any data  ,turn to our old table
            //新表旧表未同步之前 需要保证用户可以取到之前的老数据
            $oldlists = M('customer_bank_info',null)
                ->field('customer_id,card_user_name,sub_contract_id,
                    card_num,reserved_mobile,usr_busi_agreement_id,
                    usr_pay_agreement_id,gate_id,bank_card_type,
                    is_default,bank_address')
                ->where($map)
                ->find();
            if($oldlists){
                Log::borrow_write("获取用户主卡".json_encode($oldlists)."    用户".$customer_id);
                return $oldlists;
            }else{
                return  false;
            }
        }
    }
}
